Keywords in Python
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.
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
- Value Keywords
- Operator Keywords
- Iteration Keywords
- Conditional Keywords
- Structure Keywords
- Returning Keywords
- Import Keywords
- Exception Handling Keywords
- Asynchronous Keywords
- 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.
Now, let’s understand the meaning of each keyword briefly,
Must Read: What is Python
Must Check: Python Online Courses & Certificates
Best-suited Python courses for you
Learn Python with these high-rated online courses
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
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)
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
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.
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
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
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
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
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
Must Check: How to use if else statement in Python?
Must Check: Conditional Statement in Python
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
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)
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
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
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
Must Check: How to use Yield() Keyword in Python?
Note:
- Generators are iterators that generate only one item at a time.
- return and yield shouldn’t be used in the same function.
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.
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
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.
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)
S
9 months ago
Report Abuse
Reply to Sk Mastanbee