Break and Continue Keywords Cannot Be Used With in
In Python, certain keywords cannot be utilized as variable or function names. Keywords are reserved words with specific functions/uses. The total number of keywords can change depending on your Python version. For example, in Python 3.7, there were only 33 keywords. In Python 3.10.4, there are about 35 keywords. In this tutorial, we'll be learning about Python keywords.
Checking for Keywords
In Python, you can use the keyword module to check for keywords. Keyword.kwlist will list all the keywords in Python.
main.py
import keyword
# this print out all the keywords
var = keyword.kwlist
print (var)
Output:
[ 'False' , 'None' , 'True' , 'and' , 'as' , 'assert' , 'async' , 'await' , 'break' , 'class' , 'continue' , 'def' , 'del' , 'elif' , 'else' , 'except' , 'finally' , 'for' , 'from' , 'global' , 'if' , 'import' , 'in' , 'is' , 'lambda' , 'nonlocal' , 'not' , 'or' , 'pass' , 'raise' , 'return' , 'try' , 'while' , 'with' , 'yield' ]
Process finished with exit code 0
If, on the other hand, you aren't sure if a word is a keyword, you can use keyword.iskeyword(s) to find out:
main.py
import keyword
word_1 = "break"
word_2 = "function"
word_3 = "variable"
# this is used to check if a word is a keyword
var_1 = keyword.iskeyword (word_1)
print (var_1)
var_2 = keyword.iskeyword (word_2)
print (var_2)
var_3 = keyword.iskeyword (word_3)
print (var_3)
Output:
True
False
False
Process finished with exit code 0
So now, let's check out several keywords!
Keyword: assert
The assert keyword is used in Python to debug. Here, a condition is passed after the assert keyword. If this condition is True, everything is fine; if, on the other hand, the condition is false, an AssertionError is raised.
Here are two distinct examples. On the first try of the except block, the condition is True, so no error is raised. In the second try of the except block, the condition (2+3 == 10) is false, and so an AssertionError is raised.
main.py
try:
assert 2+3 == 5
print ( "Assert 2+3 == 5 did not raise an AssertionError" )
except AssertionError:
print ( "Assert 2+3 == 5 did raise an AssertionError" )
try:
assert 2+3 == 10
print ( "Assert 2+3 == 10 did not raise an AssertionError" )
except AssertionError:
print ( "Assert 2+3 == 10 raised an AssertionError" )
Output:
Assert 2+3 == 5 did not raise an AssertionError
Assert 2+3 == 10 raised an AssertionError
Process finished with exit code 0
Keywords: pass, continue, and break
The pass keyword results in a null operation; it basically does nothing. It is typically used when beginning to write code as a placeholder. Basically, it will bypass it.
main.py
class person( ):
pass
Output:
Process finished with exit code 0
On the other hand, the continue keyword is used to end the iteration in a for or while loop and subsequently move on to the next iteration. So, if the continue keyword is used, it will skip an iteration.
main.py
numbers = [ 10 , 15 , 20 , 25 , 30 , 35 , 40 ]
for numb in numbers:
if numb/2 == 5:
continue
print (numb)
Output:
15
20
25
30
35
40
Process finished with exit code 0
In this example, we're saying if a number divided by 2 equals 5, then continue, and 10 divided by 2 is equal to 5, so it skipped it.
The break keyword is used to break out of a loop
main.py
i= 1
while I < 9:
i = i + 1
if i != 5:
print (i)
if i == 5:
break
print ( "Outside the loo" )
Output:
2
3
4
Outside the loop
Process finished with exit code 0
As you can see, when it hits 5, it breaks out of the loop.
Keywords: if, else, and elif
We've all encountered the if, else, and elif statements. These are the basics.
main.py
numbers = [ 15 , 20 , 25 ]
for numb in numbers:
if numb > 20:
print ( "%s is greater than 20" % (numb) )
elif numb < 20:
print ( "%s is less than 20" % (numb) )
else:
print ( "%s is equal to 20" % (numb) )
Output:
15 is less than 20
20 is equal to 20
25 is greater than 20
Process finished with exit code 0
Keywords: try, except, and finally
Try except statements are used to catch errors. So, we say try this, and if it fails, we can catch the error in the except statement.
main.py
x = "2"
try:
if x == "2":
print ( "first try block went alright" )
except:
print ( "Error occurred" )
try:
if x/0 == 1:
print (x/2 )
except TypeError:
print ( "There was a TypeError in the second try block" )
Output:
first try block went alright
There was a TypeError in the second try block
Process finished with exit code 0
As you can see, in the first block, there was no error, so the try block was executed, and the except block was ignored. In the second try block, there was an error, and this error was caught by the except block.
The finally block is executed after the try and except block. It is always executed regardless of what happens.
main.py
try:
i = 4
b = i/0
print (b)
except ZeroDivisionError:
print ( "Error" )
finally:
print ( "After the try except block" )
Output:
Error
After the try except block
Process finished with exit code 0
Keywords: is and in
The is keyword is used to determine if two objects are identical.
main.py
x = [ "car" , "race" , "accident" ]
y = [ "car" , "race" , "accident" ]
print ( x is y )
Output:
False
Process finished with exit code 0
The latter is so because these lists are mutable and allocated separately in memory.
The in keyword is used to check if a value is contained within a list or something similar.
Main.py
x = ["car", "race", "accident"]
if "car" in x:
print ("The word car is in the list x")
else:
print ("The word car is not in the list x")
Output:
The word car is in the list x
Process finished with exit code 0
Keywords: True, False, and None
True and False are Boolean values; None is a null value.
Main.py
print ( None == 0 )
print ( None == False )
print ( None == None )
print ( 2+3 == 5 )
print ( 2+3 == 10 )
Output:
False
False
True
True
False
Process finished with exit code 0
So, this means that None is not equal to 0, not equal to False, and is a value of its own.
Keywords: and, or, and not
These are quite straightforward. And is and, or is or, and not is used to negate something.
main.py
a = 3
b = 5
c = 30
if a > 1 and a6 or b < 20:
print ( "b is greater than 6 or less than 20" )
else:
print ( "b is neither greater than 6 nor less than 20" )
print ( not True )
Output:
a is between 1 and 20
b is greater than 6 or less than 20
False
Process finished with exit code 0
Remember that for "and", both statements need to be true to return a True. For "or", you only need one to be True.
Keywords: for and while
Both for and while are used for looping. We use for when we know how many times we want to loop. We use while when we want the loop to keep going until it hits a break or a pre-set termination point.
main.py
# for loop
x = [ "car" , "race" , "accident" ]
for members in x:
print (members)
# while loop
i= 1
while i< 3:
i = i + 1
print (i)
Output:
car
race
accident
2
3
Process finished with exit code 0
Keywords: import, from, and as
We all know and use the keyword import. It is used to import modules. Also, we know "from" since it's used in the import statement. The as keyword is used for aliasing.
main.py
from keyword import kwlist
from keyword import iskeyword as key
print (kwlist)
print (key( "race" ) )
Output:
[ 'False' , 'None' , 'True' , 'and' , 'as' , 'assert' , 'async' , 'await' , 'break' , 'class' , 'continue' , 'def' , 'del' , 'elif' , 'else' , 'except' , 'finally' , 'for' , 'from' , 'global' , 'if' , 'import' , 'in' , 'is' , 'lambda' , 'nonlocal' , 'not' , 'or' , 'pass' , 'raise' , 'return' , 'try' , 'while' , 'with' , 'yield' ]
False
Process finished with exit code 0
So here, the keyword as is used as an alias for the word iskeyword.
Keywords: class, def, return, and yield
The class keyword is used to put together data and functions. The def keyword is used to define a function. And return is used to return a value.
main.py
class Area:
# function
def __init__ ( self , width, height):
self.width = width
self.height = height
def rectarea( self ):
return self.width * self.height
var = Area( 3 , 4 )
print (var.rectarea ( ) )
Output:
12
Process finished with exit code 0
Unlike return that gives an output and subsequently stops, yield will provide an output and continue. The yield keyword is used within a function and returns a generator.
main.py
# return function
def returnfunc( ):
for i in range ( 3 ):
print ( "returnfunc: %s" % i)
return i
returnfunc( )
# yield function
def yieldfunc( ):
for i in range ( 3 ):
yield i
for member in yieldfunc( ):
print ( "yieldfunc: %s" % member)
Output:
returnfunc: 0
yieldfunc: 0
yieldfunc: 1
yieldfunc: 2
Process finished with exit code 0
Notice how for the yield scenario, it keeps going, whereas for the return scenario, it stops once it hits the return keyword.
Keywords: global and nonlocal
The global keyword can be accessed anywhere. Typically, a variable outside a function can easily be read and printed from within a function. But, when it comes to modifying it, you need to use the keyword global, else you'll get an error.
main.py
x = 8
try:
def add( ):
x = x + 8
print (x)
add( )
except UnboundLocalError:
print ( "Error raised because you cannot mess around with a global variable in a local context" )
try:
def minus( ):
global x
x = x-4
print (x)
minus( )
except UnboundLocalError:
print ( "Error raised" )
Output:
Error raised because you cannot mess around with a global variable in a local context
4
Process finished with exit code 0
The nonlocal keyword is used with nested functions.
main.py
# without using nonlocal
def outer_func( ):
x = 2
def inner_func( ):
x = 3
print ( "inner_func: %s" % x)
inner_func( )
print ( "outer_func: %s" % x)
outer_func( )
# now using nonlocal
def outer_func2( ):
x = 10
def inner_func2( ):
nonlocal x
x = 20
print ( "inner_func2: %s" % x)
inner_func2( )
print ( "outer_func2: %s" % x)
outer_func2( )
Output:
inner_func: 3
outer_func: 2
inner_func2: 20
outer_func2: 20
Process finished with exit code 0
Keyword: del
The del keyword is used to delete.
main.py
x = [ "race" , "car" , "accident" ]
del x[ 2 ]
print (x)
Output:
[ 'race' , 'car' ]
Process finished with exit code 0
Keyword: with
The with keyword simplifies the code.
main.py
with open ( 'file.txt' , 'w' ) as file:
file.write ( "LinuxHint" )
Output:
Process finished with exit code 0
Keywords: async and await
Here, the function will run with a five-second gap between the first print statement and the second.
main.py
import asyncio
async def ayncfunc( ):
print ( 'First statement' )
await asyncio.sleep ( 5 )
print ( 'Second statement' )
asyncio.run (ayncfunc( ) )
Output:
First statement
Second statement
Process finished with exit code 0
Keyword: raise
The raise keyword is used to raise an exception or an error.
main.py
x = [ 5 , 10 , 15 , 20 ]
for members in x:
z = members/5
if z == 1:
raise Exception ( "you got a 1" )
Output:
raise Exception ( "you got a 1" )
Exception: you got a 1
Process finished with exit code 1
Keyword: lambda
The lambda keyword is used to create a function with no name.
main.py
a = lambda x, y, z: x + y + z
print (a( 1 , 2 , 3 ) )
Output:
6
Process finished with exit code 0
Conclusion
Python keywords are crucial words that cannot be used as variable or function names. There are 35 keywords in Python 3.10.4, and each keyword is as important as the rest. In this tutorial, we learned about each one of these 35 keywords. So, use each one efficiently!
charbonneauanscialtat.blogspot.com
Source: https://linuxhint.com/python-keywords/
0 Response to "Break and Continue Keywords Cannot Be Used With in"
إرسال تعليق