Keywords in Python

·

24 min read

Keywords in Python

Python Keywords are Python-reserved words that serve a specific purpose and cannot be assigned to serve another purpose. It is very frustrating when an error is raised after writing lines of code and running a program. Therefore, it is important to know the standards for writing clean code.

There are various naming conventions in Python; a key one is not using Python keywords when assigning user-defined names. Python 3.11 has 35 keywords that are mentioned in the table below. This article will help you understand how they should be used with relevant examples.

Table 1. Python Keywords

True

not

yield

else

class

nonlocal

False

in

lambda

try

del

def

None

for

async

except

pass

return

and

while

await

raise

with

from

or

continue

if

assert

as

import

is

break

elif

finally

global

The True and False Statements

Python has four common data types namely, Strings, Booleans, Float (decimals) and Integers. Python Boolean is used to represent the true value of an expression. All objects in Python have a Boolean value that is either True or False.

True represents any nonzero or any nonempty collection object for example a list or dictionary. The number one is used to represent True.

False represents zero or any empty collection object for example a list or dictionary. Let us use the Python bool( ) function used to return or convert a value to a Boolean to give examples.

Example 1

>>> bool(0)
False
>>> bool(1)
True
>>> bool({})
False
>>> bool([2, 4, 6])
True

True and False values can also result from comparison operations. The table below shows comparison operators and their descriptions.

Table 2. Comparison Operators

Operator

Description

A < B

A less than B

A <= B

A less than or equal to B

A > B

A greater than B

A >= B

A is greater than or equal to B

A == B

A is equal to B

A != B

A is not equal to B

A is B

A is the same object as B

Example 2

>>> 1 == 1
True
>>> 1 != 1
False
>>> 1 > 10
False
>>> 1 < 10
True

The None Keyword

None in Python doesn’t represent any value. This does not mean that it can be defined to be 0. As explained earlier 0 is represented by the Boolean value False.

None is returned when a function is called and there is no return statement to return a value.

Example

def no_value():
    print("No value")

x = no_value()
print(x)

Output

None

Comparison Operator Keywords: and, or, is, not

Comparison operators implement a particular concept (False, equal, not equal, or True) of what the value of an object is. Indirectly they are defining the value of an object. We will see how this occurs through the and, or, is, not keywords.

Table 3. Comparison Operator Keywords

Operator

Description

A and B

First evaluates A; if A is false, its value is returned; otherwise, B is evaluated and the resulting value is returned.

A or B

First evaluates A; if A is true, its value is returned; otherwise, B is evaluated and the resulting value is returned.

A is B

Same object

A is not B

A is not the same object as B

not A

If A is false it yields True; otherwise False.

It is important to note that comparison of singletons like None should always be done with is or not keywords never equality operators ( == ), ( != ).

The and Keyword

As described in table 3, when the and operator is used the first object (a) is evaluated, if false the first object (a) is returned; otherwise, the second object (b) is returned. Here is an example to illustrate.

>>> a = 0
>>> b = 1
>>> a and b
0

The or Keyword

When the or operator is used object (a) is evaluated; if true object (a) is returned otherwise the second object (b) is returned. Here is an example to illustrate this.

>>> a = 0
>>> b = 1
>>> a or b
1

The is Keyword

This keyword identifies if two objects are the same; not to be confused with the (==) operator which checks if two values are the same.

The two operators cannot be used interchangeably because two things can be considered equal but not the same object in memory.

This is why is keyword is used to compare singletons; objects that appear once in memory like None.

>>> def no_value():
...     print("No value")
   
>>> x = no_value()
No value
>>> print(x)
None
>>> x is None
True

Using the same example we used to illustrate how None is returned when there is no value returned from a function; we can compare if variable x is the same object in memory as None. The output is the Boolean value True.

More on the def keyword and functions can be found here.

The not Keyword

If a variable is false the not Keyword will yield the Boolean value True, and if a variable is true the not keyword will yield the Boolean value False. Here is an example to illustrate.

>>> a = 0
>>> bool(a)
False
>>> not a
True

Membership Test Operator: in

The in keyword tests for membership. a in b evaluates to True if a is a member of b, and if not a member it evaluates to False.

We can use this operator to check if a letter is in a word or if an element is in a container such as a list, tuple or dictionary.

>>> a = [1, 2, 3, 4]
>>> 4 in a
True

Iteration Keywords

When building a program we might require it to repeat certain tasks. This repetition is made possible by loop statements that allow us to execute the same block of code as much as is needed to complete a task.

Python has two main loop statements: the for loop and the while loop

The for Statement

This loop iterates (repeats) each item in a variable for example a list, dictionary, tuple or string. The for statement has a variable which it works on, and a list of parameters it works with.

For example, every letter for the string “Python” will be printed once the program is run.

Example 1

for letter in "Python":
  print(letter)

Output

P
y
t
h
o
n

Example 2

# Iteration through a list
Teams = ["Manchester United", "Real Madrid", "Bayern Munich"]

for team in Teams:
  print(team)

Output:

Manchester United
Real Madrid
Bayern Munich

Example 3

Car_brands = ["Mercedes", "Toyota", "BMW"]

for car in Car_brands:
  print("I love " + car)

For every item in the list the programs repeats the action of adding I love before the item.

I love Mercedes
I love Toyota
I love BMW

The while Statement

A While loop allows us to execute a block of code again and again as long as the condition we’ve set remains true. The moment the condition becomes false the iteration stops.

The syntax for a while loop is:

while expression:
      indented statement(s)

Example 1

n = 0

while n < 5:
  n += 1
  print(n)

Output:

1
2
3
4
5

The else keyword is used in loop statements to specify code to be run when the loop exits normally.

Example 2

n = 0

while n < 5:
  n += 1
  print("Less than or equal to 5")
else:
  print("Greater than 5")

Output

Less than or equal to 5
Less than or equal to 5
Less than or equal to 5
Less than or equal to 5
Less than or equal to 5
Greater than 5

Loop Control Statements

These statements determine when a loop can continue or terminate. Without these statements, the interpreter will not get out of the loop or the loop will proceed without interruption.

We have the following control statements: continue statement and break statement.

The continue Statement

This statement disrupts the normal sequence of a loop by stopping the current iteration and moving to the next.

Example

i = 0

while i < 5:
  i += 1
  if i == 3:
      continue
  print("Less than or equal to 5")

The result is that the third iteration will be skipped and the loop will continue to the next iteration.

Output

Less than or equal to 5
Less than or equal to 5
Less than or equal to 5
Less than or equal to 5

The break Statement

A break statement stops the loop even if the while condition is true.

Example

i = 0

while i < 5:
  print(i)
  if i == 3:
      break
  i += 1

Output:

0
1
2
3

Note that a single equal sign (=) in this example is used to assign a value to a variable and the double equal sign (==) is used to indicate equality.

The def Statement

In Python the def statement is used to define a function. Functions are a collection of code that executes a command and perform a task. A function gives us the ability to divide and order code; making it organised and readable.

Once we have introduced a function into our program we need to call the function. Calling a function simply means using the function name and giving it an input to compute.

function_name - The function you want to use.

Parameter- This is a variable that is used inside parentheses when defining a function.

Argument - This is a value that is passed when calling a function

Through the def keyword we can create our own functions. The syntax would be

def function_name(parameter1, parameter2):

Remember to always add a colon (:) at the end of a line of code that starts with def

The return Statement

Functions work in the background and will not normally show the results of the computation unless the return statement is used.

It is important that we return a value to confirm that the computation performed on the parameters is what we expected**.**

Any code nested within the function and placed under return will not work. The return statement breaks out of a function.

Example

def hello(name, msg):
  return name + msg


print(hello("Steve, ", "Good Morning."))

Output

Steve, Good Morning.

Arguments in Python

When calling a function the parameters that we pass are called an argument. In the previous example, we passed “Steve” and “Good Morning.”

Here are examples of argument formats that will help you understand how to use the def operator.

Positional Arguments

Example

def hello(name, msg):
  return name + msg

We have two parameters name and msg in our function definition. When calling the functions the arguments should be in the same order as the parameters.

print(hello("Steve, ", "Good Morning."))

In this case argument “Steve” is assigned to parameter ‘name’ and argument “Good morning” is assigned to parameter ‘msg’.

Default Arguments

In this format the values have already been provided in the function definition. Default arguments should follow non-default arguments. If we pass an argument when calling the function, the default value will be changed to the new value.

Example 1

def hello(name, msg="Good Morning."):
  return name + msg


print(hello("Steve, "))

Output

Steve, Good Morning.

If a different value is passed when calling the function, overriding of the default argument occurs.

Example 2

def hello(name, msg="Good Morning."):
  return name + msg


print(hello("Steve, ", "Good Afternoon."))

Output

Steve, Good Afternoon.

Keyword Arguments

When calling a function a value can be assigned to a specific parameter. This type of argument is known as a keyword argument.

Example 1

def num(a, b, c):
  print(a, b, c)


num(a=2, b=4, c=6)

Output

2 4 6

It is important to note that, unlike positional arguments where the position matters for keyword arguments what matters is the keyword. This means you can order the parameters in any order you see fit.

Example 2

def num(a, b, c):
  print(a, b, c)


num(c=2, b=4, a=6)

Output

6 4 2

When calling a function we can have both positional arguments and keyword arguments. The positional argument should always come before a keyword argument to avoid raising a SyntaxError.

Arbitrary Arguments

There are two types of arbitrary arguments; arbitrary positional arguments and arbitrary keyword arguments.

1. Arbitrary Positional arguments

In the syntax of the function an asterisk (*) is placed before the parameter. Since we do not know the number of arguments that will be passed; this format allows us to collect extra positional arguments as a tuple**.**

Example 1

def add(*a):
  result = 0
  for i in a:
      result = result+i
  return result


print(add(1, 2, 3, 4, 5, 6, 7))

Output:

28

It is important to note that after the arbitrary positional argument we can only have a keyword argument. If we follow up with a positional argument we will get a TypeError.

Example 2

def num(*args, b):
  for arg in args:
      print(arg)
  print(b)


num(2, 4, b=6)

Output

2
4
6

Note that the word args is used as a collective name to represent positional arguments.

2. Arbitrary Keyword arguments

In the syntax of the function a double asterisk(**) is placed before the parameter. Since we don’t know the number of arguments that will be passed; this format allows us to collect parameters into a dictionary.

Example 1

def student(**kwargs):
  print(kwargs)


student(name="Eric", course="Environmental Science", GPA=3.5)

Output

{'name': 'Eric', 'course': 'Environmental Science', 'GPA': 3.5}

Example 2

We can unpack a dictionary using the double asterisks(**)

def student(name, course, GPA):
  print(name, course, GPA)


my_dict = {'name': 'Eric', 'course': 'Environmental Science', "GPA": 3.5}
student(**my_dict)

Output

Eric Environmental Science 3.5

Note that the word kwargs is used as a collective name to represent keyword arguments.

The yield Statement

We have discussed how the return statement exits the enclosing function and returns an expression value as the result of function computation. This is convenient when dealing with stored data that doesn't overwhelm computer memory.

Since memory is a limited resource, we use generator functions to allow us to deal with big datasets in manageable chunks. These are functions that return an object that can be iterated over. They generate the items inside the object one at a time and only when we ask of it.

The yield statement allows us to pause and yield a generator object. After the yield statement, the generator function remembers where it left off and continues to the next iteration when called upon.

We can understand this concept using the built-in next( ) function.

Example

>>> def generator_1():
...          num = 0
...          while num <= 5:
...                  yield num
...                   num += 1

If we go past the specified range the generator function raises a StopIteration exception as it exits the iteration.

Traceback (most recent call last):
  File "<stdin>", line 16, in <module>
StopIteration

lambda expressions

The lambda expression is an anonymous function that is defined without a name. As discussed earlier the def statement has a function name. This is one key difference between a def statement and a lambda expression.

The syntax of a lambda expression is lambda argument: expression

This one-line expression is used when we want a simple function that will be used once in our code. It can also be used as an argument in higher-order functions.

A higher-order function can take one or more functions as arguments. For this article, built-in functions map( ) and filter( ) will be used to illustrate the use of a lambda expression. We will also use the reduce( ) function from the functools module.

Example 1

Using the map ( ) function to multiply all items in this list by 2

list_1 = [2, 4, 6, 8, 10]
list_2 = map(lambda x: x*2, list_1)

print(list(list_2))

Output

[4, 8, 12, 16, 20]

Example 2

Using the filter( ) function to filter odd number from a list.

list_1 = (range(10))
list_2 = filter(lambda x: x%2, list_1)
print(list(list_2))

Output

[1, 3, 5, 7, 9]

Example 3

Using the reduce( ) function to compute from a sequence of successive elements

from functools import reduce

Output

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

The async/ await Keywords

To understand how these two keywords are used in Python there are a few definitions we have to understand. The first concept that is important to understand is concurrency.

Concurrency- This is the ability to run multiple tasks in an overlapping manner. This is different to parallelism which refers to the ability to perform various operations at the same time.

Coroutines- This is a function that is introduced by the syntax async def This is a function that can suspend its execution and can donate control to another coroutine.

Asynchronous- Asynchronous routines are able to pause while another routine runs as they wait for their ultimate result to return.

The keywords async and await are used together to help you declare, build, execute and manage asynchronous code.

Syntax

async def a():
    b = await c()
    return b

#or

async def a():
    print()
    await b()
    print()

When Python encounters await c( ) expression within the async function a( ), it causes suspension of a( ) until the result of f( ) is returned. This allows something else to run as a( ) is paused and f( ) is returning a value.

It is important to note that async def can be used with await, return or yield. When using await you can call the asynchronous function or store the results in a variable.

Control Flow Keywords: if, elif, and else

The if Statement

Normally when code is executed, the interpreter goes through it line by line. When we need to execute a code that is lines ahead we will need to break that sequence and move to the line we want to execute. The if statement gives us the ability to control the flow of code execution.

The if statement is used when we want a line of code to be executed once a condition has been met. If a condition is true certain code will be executed if false it will skip to another section of the code.

To understand this better let’s say we want to assign grades to a variety of scores.

Example

score = float(input("Please Enter your Score: "))


def grade_score(scores):
  if scores >= 80:
      letter = "A"
  elif scores >= 70:
      letter = "B"
  elif scores >= 60:
      letter = "C"
  elif scores >= 50:
      letter = "D"
  else:
      letter = "E"
  return letter


print(grade_score(score))

The input the program receives determines which line of code will be executed. In this example, the input will be a score of 85 making the if condition if score >= 80: letter = "A" true.

Output

Please Enter your Score: 85
A

The elif and else Keywords

As demonstrated in the example above elif is used after if to accommodate alternatives of the if condition being true. The else keyword, on the other hand, is used in an if and else code block when we want to execute a line of code when a condition is false.

Exception Handling Keywords: try, except, finally, raise, assert

The try and except Keywords

In Python, there are at least two kinds of errors: syntax and exceptions. A syntax error occurs when the structure of a line of code is incorrect. For example, a missing colon (:) at the end of an if statement.

In some situations, an error may occur even when the syntax is accurate. When an error occurs after executing a statement or expression, we refer to it as an exception. The output will be an error statement specifying the type of exception. For example, if we divide 10 by 0.

>>> 10/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

The exception type error here would be, ZeroDivisionError.

An exception stops a program from running. The try statement enables us to anticipate the exception and execute an action in case the exception occurs. Let’s see how this works through this example.

def divide(a, b):
  try:
      result = a/b
  except ZeroDivisionError:
      print("Division by zero!")
  else:
      print("Answer: ", result)
  finally:
      print("Division done")


print(divide(10, 0))

Since an exception has occurred the except clause will run.

Division by zero!
Division done

If there is no exception then the try clause will run.

def divide(a, b):
  try:
      result = a/b
  except ZeroDivisionError:
      print("Division by zero!")
  else:
      print("Answer: ", result)
  finally:
      print("Division done")


print(divide(10, 10))

Output

Answer:  1.0
Division done

The finally Keyword

It is important to note that on all the outputs the finally clause is present. The finally clause executes as the last task, marking the end of a try statement. The finally clause runs whether or not an exception occurs.

Table 4: Various try statement formats

Clause Format

Interpretation

except:

Catch all exceptions

except type:

Catch one specific exception

except type as value:

Catch an exception and its instance

except (type 1, type 2):

Catch any of the exceptions specified

except(type 1, type 2) as value:

Catch any of the exceptions and its

else:

Run if no exceptions are raised

finally:

Always run this block on the way

The raise Statement

This statement is used to trigger an exception when a certain condition is met. It can be used to raise built-in exceptions or user-defined exceptions.

Example

a = int(input("Enter number: "))
if a < 0:
  raise Exception("Number should be positive")

If the number the user inputs is less than 0, it will raise the exception.

Enter number: -1
Traceback (most recent call last):
  File "<stdin>", line 36, in <module>
    raise Exception("Number should be positive")
Exception: Number should be positive

The assert Statement

If an expression is false, the assert statement raises an AssertError. This is useful in performing debugging checks. We can pass a message that specifies the error.

Example

a = int(input("Please enter number: "))
assert a <= 0, "a is positive"

Assertion is that a is less or equal to 0. If the user inputs a number that is greater than 0 the assertion will be false and an AssertionError will be raised.

Output

Please enter number: 10
Traceback (most recent call last):
  File "<stdin>", line 35, in <module>
    assert a <= 0, "a is positive"
AssertionError: a is positive

The class Statement

An object such as a phone or a student can have various attributes associated with it. In order to make our programs organised and efficient we need a way to store these data types in Python.

A class is created to store these different attributes of an object, for example, a student can have a name, age, course or year of study. The class defines the kind or type of data the objects contain.

The syntax of a class statement is

class class_name():

Anything indented under the class or typed after the colon(:) will be considered to be in the class.

Let’s create a student class and define the attributes using the initialised function init(self):

class Student:

  def init(self, name, course, gpa, is_in_finalyear):

The init (double underscore) function is a Python constructor whose only purpose is to allow us to map out attributes of an object with different data types such as String(name), Float(gpa) or Boolean(is_in_finalyear).

Courtesy of the Student class, we have the student data type. Name, course, gpa, and is_in_finalyear are parameters and therefore we still have to create an object (an actual student who has all these attributes).

The from and import Keywords

We can create a student object by importing the student class. Here we can see how the import statement is used with the keyword from.

The from keyword when used with the import statement is used to import something specific from a module.

from Student import Student

from Student(student file) import Student(the student class we created).

After importing the Student class, we can create our object. Let’s say our student is called Eric, pursuing the course Environmental Science, has a GPA of 3.8 and is not in his final year.

from Student import Student

student_1 = Student("Eric", "Environmental Science", 3.8, False)

We can access attributes from the student object by using a print statement for example

print(student1.name)
print(student1.course)

The output will display the object attributes.

Eric
Environmental Science

The del Statement

The del keyword deletes variables, keys in a dictionary, slices and attributes. The following syntax can apply.

del object_name
del name[]
del name[a:b]
del name.attribute

Example

Using del to delete an element within a list.

example_list = [2, 4, 6, 8, 10, 12]

del example_list[0]

print(example_list)

Output

[4, 6, 8, 10, 12]

The pass Statement

This is a placeholder statement that does nothing when executed. It is used when syntactically necessary for situations where empty code will bring about an error.

Let’s recap on the for loop example we did earlier where we printed each letter of the word Python. If we omit the print statement indented after the for loop we will get an IndetationError.

File "<stdin>", line 2
   
IndentationError: expected an indented block after 'for' statement on line 2

But when we use the pass statement, nothing will be printed and no error will appear. Here is the syntax.

for letter in "Python":
    pass

The with Statement

In Python, the with statement relates closely to context managers. It wraps a nested block of code in a context manager which handles entry and exit actions for the execution of a block of code.

Syntax

with context manager() as variable:
    statement

The with statement provides a simple way to deal with common resource patterns such as files. Opening a file with the open( ) function would involve acquiring a file, opening it, executing a statement and closing the file.

Using the with statement guarantees that entry actions and exit actions are run whether an error occurs or not. The as clause ensures that the expression or context manager returns a value that will be assigned as an alias.

Example

with open("text") as test_file:
  for name in test_file:
      print(name.strip())

Output

Tom
Lucy
Steve
Ann
Mary

The as Keyword

In the previous topic we’ve discussed how the as keyword can be used with the with keyword. It can also be used to catch an exception and its instance.

Example

def division(a, b):
  try:
      result = a/b
  except ZeroDivisionError as err:
      print(err)
  else:
      print("Answer: ", result)
  finally:
      print("Division Done")


division(10, 0)

Output

division by zero
Division Done

The as keyword can be used to assign a module an assumed name. For example, when importing packages we can use aliases.

Example

import pandas as pd
import numpy as np

The global Statement

To understand how the global statement works it’s important that we understand what a global variable is and where it exists.

A global variable exists in the global scope. This scope contains all of the names (variable or object) that are defined at the top level of a program. Variables in the global scope can be accessed anywhere within your code.

The scope of a variable is determined by where a variable is placed within your code. If your variable is defined within a function then it is known as a local variable. These names are only visible within that function. An example will make this clearer.

Example

a = "global"


def my_func():
  b = "local"
  print(b)


my_func()

Output

local

In this example variable a is a global variable in the global scope and variable b is a local variable in the local scope.

The global variable can be accessed within the function but we cannot modify it unless we use the global statement. The global statement allows you to create or change a global variable within a function or class.

The syntax is global name. The name used within the function or class will now be referenced as a global variable whether the name is assigned or not or whether it exists or not.

Example 2

a = "Lets go"


def add_string():
  global a
  a = a + " Manchester United"
  print(a)

add_string()
add_string()
add_string()

Output

Lets go Manchester United
Lets go Manchester United Manchester United
Lets go Manchester United Manchester United Manchester United

The global statement allows us to freely modify the global variable a. It is important to note that modification of global variables is bad programming practice. It is better to use unique variables within functions to make it easier to identify problems within your code. Best practice would be to use global variables that don’t change throughout your code.

The nonlocal Statement

Where you assign or define a name (variable or object) in your code, determines visibility and scope. We’ve looked at the positioning and visibility of a global variable and how it compares to a local variable.

In this section, we will discuss variables that exist in the outer or enclosing function and how we can modify them. These variables are known as nonlocal variables.

Example

def outer_func():
  b = "nonlocal"

  def inner_func():
      nonlocal b
      b = b + " local"

  inner_func()
  print(b)


outer_func()

Output

nonlocal local

Using the nonlocal keyword the nonlocal variable b was modified within the inner function.

Conclusion

Reaching the end of this article means you have general knowledge of Python Keywords. Building on this knowledge is important so as to be fluent in the Python language.

This article is a great starting point as it equips you with an understanding of Python Keywords and has relevant examples of their usage. Hopefully, you will use it as a reference point to shape your appreciation of the Python language.