Keywords in Python

Keywords in Python

10 mins read2K Views 1 Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Mar 20, 2023 12:15 IST

Python has set of keywords that are reserved words, that can’t be used for variable name, function name, or any other identifiers. In this article, we will briefly discuss all about keywords in Python with examples.

2022_06_MicrosoftTeams-image-211.jpg

In any programming language, there are some special words that can’t be used as variables and have specific meanings such special words are known as keywords. This article will briefly discuss about keywords in Python with examples.

Python has more than 10 different types of keywords such as: Value, Operator, Iteration, Conditional, Structure, Returning, Import, Exception Handling, Asynchronous, and Variable Handling Keywords. We will discuss all of them one by one.

Table of Content

  1. Value Keywords
  2. Operator Keywords
  3. Iteration Keywords
  4. Conditional Keywords
  5. Structure Keywords
  6. Returning Keywords
  7. Import Keywords
  8. Exception Handling Keywords
  9. Asynchronous Keywords
  10. Variable Handling Keywords

Python keyword is specially reserved words with specific meanings and purposes. They are different from built-in functions and types.

Keywords are the building blocks of any python program. 

Currently, there are 36 keywords in Python.

2022_06_python_keywords.jpg

Now, let’s understand the meaning of each keyword briefly,

Must Read: What is Python

Must Check: Python Online Courses & Certificates

Value Keywords – True/False/None

Every value in python is either True or False. True/ False is the Boolean value in python programming.

True

If a statement is true, it will print “True”. It is used to represent the Boolean True.

Example

print(5 == 5)
print(6 < 9)

Output

2022_07_image.jpg

False

If a given statement is false, it will print “False”. It is used to represent the boolean False.

Note: True/False can be assigned to variables and compared directly.

Example

print(5 == 6)
print(6 > 9)
2022_07_image-1.jpg

None:

It is immutable in nature and represents no value. It can be used to mark the missing values and results, and even default parameters where it’s a much better choice than mutable types.

Example

def divisible_function(num):
    if num % 5 == 0:
        return True
x = divisible_function(67)
print(x)

Output

2022_07_image-2.jpg
Variables in Python
Variables in Python
In this article, we will discuss variables in python, how to name them and how to work with the variables.
Functions in Python
Functions in Python
By Varun Dwarki
Python Dictionary Practice Programs For Beginners
Python Dictionary Practice Programs For Beginners
Working with Python dictionary types can seem slightly difficult if you are not familiar with its features. The best way to master it is by solving problem statements. It is...read more

Operator Keyword: and/or/not/is/in

and

it is a logical operator and will return to True, only if both the operands are True.

or

It will return True if any of the operands are true

Truth Table for “and”, “or”

A B A and B A or B
True True True True
True False False  True
False True False True
False False False False

not

It is used to get the opposite Boolean value of a variable

truth table for “not”

A ~A (not A)
True False
False True

is

 It is used as an identity check. It determines whether two objects are identically the same.

If two objects are exactly the same, it will return True or else it will return False.

in

It is used to find or search an element or sequence, it will return True or False indicating whether the element or sequence exists or not.

Tutorial – for Loop in Python
Tutorial – for Loop in Python
Let’s read about for Loop in Python in the below tutorial.
String Formatting in Python
String Formatting in Python
In this article we discussed different techniques of string formatting in python like modulo operator, built-in format and f-string.
Array Manipulation Using NumPy
Array Manipulation Using NumPy
NumPy is a foundation library for scientific computations in Python, literally standing for Numerical Python. It contains sophisticated functions and tools for integrating with other programming languages as well. During...read more

Iteration Keywords: for/while/break/continue

In any programming language loop is one of the most important concepts. A loop statement allows to execution of a statement or group of statements multiple times. In Python, there are different keywords used to create and work with loops.

for

It is mainly used when we know the number of times we want to iterate. It can be used with any type of list or string. It traverses through every element of the list.

Example

# use of for loop
 
Months = ["Jan","Feb","Mar","April","May","June", "July", "August", "September", "October", "November", "December"]
for m in Months:
		print(m)

Output

2022_07_image-3.jpg

Must Check: for loop in Python

while

statement under while loop executes until the condition for the while loop evaluates to false or break. 

In simple terms, the block following the while statement will continue to be executed over again and again as long as the condition that follows the while keyword is True.

Example

# use of while loop
x = 0
while x <= 10:
    print (x)
    x = x+1

Output

2022_07_image-4.jpg

Must Check: Python while loop

break

It is used to control the flow of the loop, i.e. if we need to exit a loop early, then we can use the break keyword.

Example

# use of break
 
for x in range (20,30):
    if x == 25:
        break
    print(x)
 

Output

2022_07_image-5.jpg

Must Check: How to use Break Statement in Python?

continue

Continue is used when we want to skip the current iteration and allow it to move to the next iteration.

Note: Both break and continue are used inside for and while loops to change their normal behavior.

Example

# use of continue
 
for x in range (20,30):
    if x % 2 == 0:
        continue
    print(x)

Output

2022_07_image-6.jpg

Must Check: How to use Python Continue Statement?

Conditional Keywords: if/else/elif

if, elif, and else are used for control flow.

if

It is used to start a conditional statement. Block of code will get executed only if, the statement after it is true.

elif

It is used with if to check multiple conditions and used with if statement for else-if operation.

else

It is used with if, elif. It executes the statement when none of the earlier conditions is True i.e. when the if statement returns false, then the else block is executed.

Example: Here, we will see a use of if, elif and else in an example:

n = int(input("Enter the number"))
 
factorial = 1
 
if n < 0:
   print("enter non-negative integers only")
elif n == 0:
   print("Factorial of 0 is 1")
else:
   for i in range(1,n + 1):
       factorial = factorial*i
   print("Factorial of",n,"is",factorial)

Output

2022_07_image-7.jpg

Must Check: How to use if else statement in Python?

Must Check: Conditional Statement in Python

Introduction To Decorators In Python
Introduction To Decorators In Python
In this article, we will discuss in detail about what are python decorator, why we need them and finally how to create python decorators.
Understanding Tuples in Python
Understanding Tuples in Python
In this guide, you will learn all about Tuples in Python: creating tuples, accessing tuple items, looping through a tuple, and other tuple operations with the help of examples.
Working with Python Numbers

Structure Keywords: def/class/pass/lambda

class

It is a collection of related attributes or methods that represent the real-world situation. A class can be defined anywhere in a program.

Example:

# create a class
 
class Employee:
#__init(): is a built-in function, used to assign the value to object properties that are necessary to do when the is being created
# __init__ is executed when the class is being initiated
 
  def __init__(self, name, department):  
    self.name = name
    self.department = department
 
e1 = Employee("AA", "Shiksha Online")
 
print(e1.name)
print(e1.department)

Output

2022_07_image-9.jpg

def

It is used to declare the user-defined function or method of a class in python.

Example

#create a function using def
 
def divison(a,b):
    print(a/b)
 
divison(2,4)
2022_07_image-8.jpg

Must Check: How to use def keyword in python?

pass

It is used as a placeholder. It is a null statement and will return nothing when it will be executed.

Example:

#pass is just a placeholder for functionality to be added later.
sequence = {'n', 'a', 'u', 'k', 'i', 'l', 'e', 'a', 'r', 'n', 'i', 'n', 'g'}
for val in sequence:
    pass

Must Check: How to use Pass Keyword in Python?

lambda

It is a function with no name(anonymous). It consists of an expression that is evaluated and returned. It doesn’t contain a return statement.

Example:

#add two number using lambda
 
x = int(input("Enter the number"))
y = int(input("Enter the number"))
 
add = lambda x, y: x + y
print (add(x, y))

Output

2022_07_image-10.jpg

Must Check: Lambda Keyword in Python

Returning Keywords: return/yield

return

It is used inside the user-defined function (a function defined with def) to exit and return a value.

Example:

def cube(num):
    return num * num * num
cube(5)

Output

2022_07_image-11.jpg

yield

It is used to end a function and returns a generator. Similar to return, it is used with a user-defined function.

Example:

n = int(input("Enter the Number"))
def generator():
    for i in range(n):
        yield i*i*i
 
g = generator()
for i in g:
    print(i)

Output

2022_07_image-12.jpg

Must Check: How to use Yield() Keyword in Python?

Note:

  1. Generators are iterators that generate only one item at a time.
  2. return and yield shouldn’t be used in the same function.
Python Sets Practice Programs For Beginners
Python Sets Practice Programs For Beginners
Python offers a rich collection of sequence object types, and sets are one of them.
Python Data Types
Python Data Types
You want to store a value, but that value can be anything. It can be a number, list of number, strings, etc. So these different type of values are stored...read more
Python Lists Practice Programs For Beginners
Python Lists Practice Programs For Beginners
Test your Python Lists knowledge with practice programs! In this blog, we will solve 12 python lists exercises for beginners.

Import Keywords: import/from/as

These keywords help to import the python modules (available in the python standard library) that are not already available.

import

It is used to import modules for use in the python program. After importing the module, you have access to all the tools in the module.

from

It is used with import to download any specific tool from any module.

as

It is used to create an alias while importing modules. It is used with import and from keywords.

Example: Here, we will show how to use import, from and as in one program

#import, from, as
 
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib as plt
%matplotlib inline
 
from sklearn.model_selection import train_test_split
 
from sklearn.linear_model import LinearRegression
 
from sklearn.tree import DecisionTreeRegressor
 
from sklearn.ensemble import RandomForestRegressor
 
from sklearn.metrics import mean_squared_log_erro

Exception-Handling Keywords: try/except/raise/finally/assert/with

Exception in python are nothing but an error that suggests something went wrong when we will execute the program. These keywords help to catch the error in the program.

try

Any exception handling block begins with a try. It will not work unless it has one of the other exceptional handling keywords.

except

It is used the try, to define what to do next when an error (exception) occurred.

Must Check: How to Use Python Try Except

raise

It is used to raise the exception.

finally

A block of code that will be executed no matter if there are exceptions or not. It is used with try and except block.

assert

It will be used to make sure that needs to be true. But couldn’t rely on them. Mainly it is used for debugging.

Must Check: How to use Python Assert Keywords?

with

 It is used to close the execution of a block of code within methods defined by the context manager (Context manager is a class that implements __enter__ and __exit methods). It is used to simplify exception handling.

Methods to Check for Prime Numbers in Python
Methods to Check for Prime Numbers in Python
Prime numbers are the building blocks of mathematics, and they have fascinated mathematicians for centuries. Regarding Python programming, there are different methods to check whether the given number is a...read more
How to Reverse a String in Python
How to Reverse a String in Python
In Python programming, strings are a sequence of characters or symbols. As a beginner practicing Python string operations, you will often come across problems that need you to work with...read more
How to Find Square Root of a Number Using Python
How to Find Square Root of a Number Using Python
The below article demonstrates different ways to find the Square Root of a Number using Python programming language.

Asynchronous Keywords: async, await

These keywords make asynchronous programming ( A type of programming that can execute more than one task at a time without blocking the main function)

These keywords are a part of the asyncio library.

async

It is used with def to define asynchronous function. It is used before def.

await

It is used in an asynchronous function to specify a point in the function in the function where control is given back to the event loop for other functions to run.

Variable Handling Keywords: del, global, non-local

del

As the name suggests, it is used to delete an object. More commonly it is used to delete indexes from a list or dictionary.

Example

#use del to remove the variable
Months = ["Jan","Feb","Mar","April","May","June", "July", "August", "September", "October", "November", "December"]
 
del Months

Output

2022_07_image-13.jpg

global

It is used to declare a global variable outside the function. If we need to change the value of a global variable inside the function, then the variable must be declared with the “global” otherwise it is not necessary to define it as “global”

non-local

It is similar to the global keyword. It is used to work with a variable inside a nested function.

Conclusion

In this article, we have discussed all 36 python keywords in detail with examples.

Hope this article will help you is your data science journey.

FAQs

What are Python Keywords?

Python keywords are special reserved words with specific meanings and purposes. They are different from built-in functions and types. These keywords are the building blocks of any python program.

What are the different types of keywords in Python?

There are more than ten different types of keywords in python. 1. Value Keyword 2. Operator Keyword 3. Iteration Keyword 4. Conditional Keyword 5. Structure Keyword 6. Returning Keyword 7. Import Keyword 8. Exceptional Handling Keyword 9. Asynchronous Keyword 10. Variable Handling Keyword

How many keywords are there in Python?

Currently there are 36 keywords in python, such as: True, False, None, And, As, Assert, async, continue, if, else, elif, except, pass, break and many more.

Can python keywords are used as variable name?

No, python keywords can't be used as a variable name, and in case, if you use it will throw syntax errors.

Can python keywords be redefined or overridden?

No, python keywords can't be redefined or overridden, as every keywords have their special meanings.

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio

Comments

(1)