Python Keywords are special reserved words that have a special meaning when interpreted by the compiler as they refer to a specific operation or meaning and can’t be used as variables.
True |
False |
None |
and |
as |
asset |
def |
class |
continue |
break |
else |
finally |
elif |
del |
except |
global |
for |
if |
from |
import |
raise |
try |
or |
return |
pass |
nonlocal |
in |
not |
is |
lambda |
To exemplify the uses of local, global, yield, and return keywords, we will use functions and for loops. You will learn about these and the other non-mentioned keywords in the future.
A variable declared inside the function's body or in the local scope is known as a local variable.
First example:
Second example:
Looking at both examples, they may look the same but they are not. The second example will actually produce an error as it tries to print the variable x but x is only defined inside the function x_value() as it is a local variable.
A variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.
In this case, both prints will work because x is defined as a global variable and therefore can be accessed throughout all the code and by all functions.
Yield is used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return.
Yield can produce a sequence of values whereas Return sends a specified value back to its caller and resulting in ending the function
The function when called will return/give back the value of x.
If a return statement is followed by an expression list, that expression list is evaluated and the value is returned like in the following example:
This will return the evaluation of a == b which is true.