Keywords and Variables

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.

Local 

A variable declared inside the function's body or in the local scope is known as a local variable.

First example:

 

def x_value():
    int = 20
    print(int)
x_value()

 

Output: 20


Second example:

 

def x_value():
    int = 20
print(int)
 

 

Output: 20

   
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.

Global

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.

 

int = 20
def x_value():
    print(int)
x_value()
print(int)

 

Output: 20
             20


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

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_value = 10
def generator():
    yield yield_value
    yield yield_value + 1
    yield yield_value + 2
//This will generate 3 values if a for runs through the values of the generator and prints them.  
for value in generator():
    print(value)

 

Output: 10
             11
             12


Return 

Yield can produce a sequence of values  whereas Return sends a specified value back to its caller and resulting in ending the function

 

def function():
    int = 30
    return int
print(function())

 

Output: 30


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:

 

left = 2
right = 2
def function():
    return left == right
print(function())

 

Output: True


This will return the evaluation of a == b which is true.

 

 

Related Tutorials