Keywords in python programming [Understand with examples]

keywords are Python’s reserved words. The keyword cannot be used as a variable name, function name, or any other identifier.
In this article, I have listed the list of python keywords with examples of each. So, if you are a programmer that writes python language and you want to know some of the keywords in python programming, this tutorial is for you.
In Python programming, you can easily print the list of keywords available in the current version of python using the snippet code below.

How to print python keywords

import keyword 
print("The list of keywords in Python is: ") 
print(keyword.kwlist)

Output
The list of keywords in python is :
[‘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’]

[Program finished]

First, you need to import “keyword” to be able to print out the list of keywords available then in the next line, we use the keyword “Kwlist” which prints out all the available keywords in your current version of python.

Below is the explanation of the printed python keywords above.

Note: The keywords printed above can be changed in several versions of Python. Some additions can be added or removed, for that reason you might not get the exact result as mine.

False

False is the boolean value when a logical statement returns false. False can also be represented using 1.

Example

print(17 = 89)

Output
False

Code explanation
In the example above, the program says 17 is equal to 89 which is false. That’s why the output is False.

None:

None is used to represent a thanks value. NB: none is different from 0 or an empty string, none is a datatype of his own.
Example

MyVariable = None
print(MyVariable)

Output
None

Code explanation
In the code example above, a None value is assigned to the variable before it’s printed using the print function. Note that a none is not the same as 0 or an empty string. None is also a Datatype on its own.

True:

is from a boolean datatype, true is returned when a logical statement returns true and it can be represented by 1.

and:

In Python, ‘and’ is a logical operator that performs two operands that returns True if both the operands are true.
Example

a=20
b=20
c=10
d=5
print(a=b and c>d)

Output
True

Code explanation
The code example gives true because the ‘and’ keyword is a Logical operator that is used to combine two conditional statements and returns true if both combined statement is true otherwise the operator returns false.

as:

As is a python keyword that’s used to create an alias. Alias is a word that’s used to represent an identifier

Example

from datetime import date as D
today = D.today()
print("Today's date:", today)

Output
Today’s date: 2022-11-15

Code explanation
In the code example above, a keyword was used to create an alias of date.

assert:

This keyword allows you to test if the code condition returns true, if the code returns true then it moves to the next line otherwise the program return error.
Example

message = "hello, good morning"
assert message= "hey", "message should be hello, good morning'"

Output

Traceback (most recent call last):
  File “/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py”, line 31, in <module>
    start(fakepyfile,mainpyfile)
  File “/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py”, line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File “<string>”, line 4, in <module>
AssertionError: message should be hello, good morning’

[Program finished]

Code explanation
In the example above, The assert keyword is used to debug and check the content of the message, and the condition was false that’s why it returns an error.

break

The Python break keyword will end the current loop in the following statement. The command will break and resume the execution in the following statement.
Example

for i in range(20):
if i > 17:
break
print(i)

Output

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

[Program finished]

Code explanation
What happens in the example above is that we check in the loop count to know if ‘i’ is greater than 17, if ‘i’ is greater than 17 then the loop execution will stop with the help of the break keyword.

class

Class keywords are used to create classes in Python programming.
Example

class greetings:
a="Hello world"
print(a)

Output
Hello world

continue

The continue keyword in Python returns the control to the beginning of the for loop and continues to the next interaction.
Example.

for i in range(20):
 if i = 17:
  continue
print(i)

Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
18
19

[Program finished]

Code explanation
In the code above. What happens in the code? The program skips the interaction when i is equal to 17 and moves to the next interaction to continue its execution.

def

it’s used to create user define functions in python programming.
Example

def test_function():
  print("message from a function")
 test_function()

Output
message from a function

Code explanation
The def keyword enables programmers to create their functions in python. In the code example above, we create test_functuon() and a message was printed from it.

del

it’s used to delete objects such as deleting list items in python.
Example

MyList=["Mango", "banana", "Orange"]
 del MyList[2]
print(MyList)

Output
[‘Mango’, ‘banana’]

Code explanation
In the code example, a list was created with three items. In the next line, the last item was removed from the list using the del keyword before it was printed on the screen.

elif

The keyword Elif is a Python method that says: “If the above conditions are not true, the program moves to the next condition to try.”

a=3
b=5
if a==b:
 print("False")
elif b>a:
 print("True")
else
 print("python")

Output
True

Code explanation
The code will return true because b is greater than a

else

This keyword contains codes to be executed if the condition in the if statement returns false.
Example

a=3
b=5
if a==b:
 print("False")
else:
 print("python")

Output
python

Code explanation
In the code example above, the program will print “python” on the screen because the condition in the if statement is false.

except

Except statement catches an exception. It is used to test code for an error that is written in the “try” statement.
Example

try:
message="hello"
message<8
except:
print("Something is wrong")

Output
Something is wrong

Code explanation
In the example above, we assign a string to a variable and later try to compare that 8 is greater than a string which will eventually result in an error but with help of the exception, the error is caught, and print a message on the screen instead.

finally

If you use it with an exception, the code block will be executed whether there is an exception or not.
Example

try:
message="hello"
message<8
except:
 print("Something is wrong")
finally:
 print("Hello, this is finally")

Output
Something is wrong
Hello, this is finally

for

For keyword is used to create a “for loop” in python.

Example

for i in range(20):
print(i)

Output
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

[Program finished]

from

The from keyword is used to import only a specified section from a module in python. Let’s write a simple python program to demonstrate how this keyword work.

Example
Let’s see how this is done.

from datetime import date
today = Date.today()
print("Today's date:", today)

Output
Today’s date: 2022-11-13

Code explanation
In the example above we only import the date from the datetime module with the help of the “from” keyword.

Global: This keyword is used to declare a global variable that can be accessed anywhere in the module of a python program.

Example

def myfunction():
 global globalMessage
  globalMessage= "Hello Global world"
#execute the function:
 myfunction()
#globalMessage can be accessible in the global scope.
  print(globalMessage)

Output
Hello Global world

Code explanation
In the code above you notice we create a variable with the word global and it was accessed outside the function because a global variable can be accessed anywhere in the module of the python program.

if

The if keyword used when you want to make a conditional statement in python programming, let’s see an example of how the “if” keyword is used.
Example

a = 78
if a == 78:
print("Hello python")

Output
Hello python

import

The import keyword is used when you want to import a statement in python programming
Example
Let’s write a simple python program to import the date and time then print it on the screen.

import datetime
currentdatetime = datetime.datetime.now()
print(currentdatetime)

Output
2022-11-14 13:22:31.016491

In

This is used to check if a value is present in an array such as a list, etc.
Example
In this example, we are going to write a simple python program to check a list of students if a particular name is in the list

StudentList = ["peace", "victory", "Liberty"] 
if "Liberty" is in StudentList:
 print("yes")

Output
yes.

is

The “is” keyword is used to check if the value in two variables is the same or not.

Example
In this example we are going to create two variables then assign values to them, then check their values using the “is” keyword to see if they are the same

a=4
b=4
print(a is b)

Output
True

Code explanation
The output of the program will be true because the value in “a” and the value in “b” are the same.

lambda

The lambda keyword is used to create an anonymous function in python programming, this function can take any number of arguments but will have only one example.

Example
Let’s write a program and create a function that multiplies any number given to it by 10.

mylambda = lambda a : a * 10
 print(mylambda(2))

Output
20

nonlocal

The nonlocal keyword is used to declare a none local variable in a python class.
Example

def firstfunction():
   myvariable = "Liberty"
  def secondfunction():
    nonlocal myvariable
     myvariable = "Peter"
secondfunction()
return myvariable 
 print(firstfunction())

Output
Peter

Code explanation
This keyword is used to work with a function inside another function which is known as the Nested function.

note

This is one of the Logical operators in python programming that returns true if a condition is false otherwise it returns false

Example

a = 3>5
print(not a)

Output
True

Or:

This is one of the Logical operators in python that is used to combine conditions and it returns true if any of the combined conditions is true otherwise false.

Example

print(3<4 or 5>2)

Output
True

Conclusion

Python keywords are words that can’t be used as a variable name or a function name or any other identifier.
In this article, I have shown you how to print out the list of keywords available in your version of python, what they mean, and also an example of each of them. If there’s anything that’s not clear to you in this article, please don’t hesitate to let us know in the comment section.

 

Leave a Reply

Your email address will not be published. Required fields are marked *