Python Keywords:
Keywords are pre-defined and reserved words in python. These words are not allowed to use by users as identifiers, function names, or variables. These keywords define the syntax of the python language.
Python keywords are case sensitive, As of now python 3.8 has 35 keywords. Different versions have different numbers of keywords, for example, python 3.7 has 33 keywords, and python 3.9 has 36 keywords.
Finding the version of Python Interpreter :
The version of our python interpreter can be found by running the below code.
Code:
Python Code
import sys
print("User Python version is :", sys.version)
Output:
User Python version is : 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]
Finding the keyword in the python version :
Keywords in our current python version can be found by running the below code
Code:
Python Code
import keyword
print("The keywords in the python version is : \n")
print(keyword.kwlist)
Output:
The keywords in the python version 3.9.1 is :
[‘False’, ‘None’, ‘True’, ‘__peg_parser__’, ‘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’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
Let’s look at the keywords in the python 3.8 version one by one :
Keywords in Python version 3.8 are : | ||||
False | class | except | in | return |
None | break | finally | is | yield |
True | await | else | import | with |
and | continue | from | lambda | while |
async | elif | for | not | raise |
assert | del | global | nonlocal | try |
as | def | if | Or | pass |
Description of the Python Keywords with examples :
- True, False
True and False are the truth values in python. They are the result of the Comparison, Logical, Identity, and Membership Operators.
Code:
Python Code
a = 3
b = 4
l = [a, b, 1, 2, 3]
# comparision operators
print(a < b)
# Logical Operators
print(b > a and a < b)
# identify operators
print(a is b)
# Member ship operators
print(a in l)
Output:
True
True
False
True
- None
None is a special constant in Python that represents the absence of a value or a null value.
None is returned by the void functions and functions in which the return statement is not encountered, automatically.
Void function returning None.
Code :
Python Code
def Nonefunction():
print("This is a void function, it returns None")
x = Nonefunction()
print(x)
Output:
This is a void function, it returns None
None
Explanation: Nonefunction is a Void function. So it returns None. We can observe that the value of x is None.
Non Void function where the return is not encountered :
Code :
Python Code
def non_void_function(a):
if a & 1:
return a
a = 4
x = non_void_function(a)
print(x)
Output: None
Explanation: If the a, is odd then the function returns a, else returns None. As a, is even it returned None.
- and, or, not:
and, or, not are Logical operators in python.
Logical Operators are used to combining the conditional Statements.
Operator | Operator Name | Description |
and | Logical AND | Returns True when both statements are True |
or | Logical OR | Returns True when any one of the statements is True |
not | Logical NOT | If the result is True, it returns False. If the result is False, return True |
Code :
Python Code
a = 45
b = 353
# Logical AND
#a < 50 (True) , b > 350 (True)
# True and True = True
print(a < 50 and b > 350)
# Logical OR
#a > 30 (True), b < 350 (False)
# True | False = True
print(a > 30 or b < 350)
# logical Not
#a > 50 (False)
# not False = True
print(not (a > 50))
Output:
True
True
True
- as
as is used to give a different name for the module while importing it into the main program.
Code :
Python Code
import math as m
print("Factorial of 5 is: ", end="")
print(m.factorial(5))
print("Gcd of 100 and 24 is: ", end="")
print(m.gcd(100, 24))
Output:
Factorial of 5 is: 120
Gcd of 100 and 24 is: 4
In the above code, we imported math as m, so wherever we use math before, we can use m now.
- assert:
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False.
Syntax
Assert condition,message
This is equivalent to
If not condition raise AssertionError(message)
Code:
Python Code
a = 3
b = 0
assert b != 0, "Divsion by zero is undefined"
c = a/b
Output:
Traceback (most recent call last):
File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 3, in <module>
assert b != 0, “Divsion by zero is undefined
AssertionError: Divsion by zero is undefined.
- break,continue
break and continue are used in the loops. The break will end the loop’s iteration whenever it is encountered, If the break is in the nested loop, then it will end the last loop in the nested loop.
Continue ends the current iteration of the loop when encountered, it does not end the whole loop. The control goes for the next iteration when the continue keyword is encountered, it doesn’t execute statements after the continue.
break Example :
Code:
Python Code
for i in range(1, 5):
if i == 3:
break
print(i)
Output:
1
2
Explanation:
Actually, the for loop should print 1 to 5 numbers. But when i is 3, if the condition is met, so break gets executed. So the for loop got ended.
Continue Example :
Code:
Python Code
for i in range(1, 5):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Explanation: The for loop should print 1 to 5 numbers. When i become 3 if the condition is met, so control goes into if block, there it encounters the continue, so without exploring further statements control goes for next iteration, so except 3 remaining numbers are printed.
- Class: The class keyword is used to define a new user-defined class.
Code:
Python Code
class keywords:
def Print():
print("This is a python keyword article")
key = keywords
key.Print()
Output:
This is a python keyword article
- def
def keyword is used to define the user-defined functions.
Code:
Python Code
def function():
print("This is Inside function")
function()
Output:
This is Inside function
- del:
Everything is an object in python. del is used to Delete the reference to an object. del can be used to delete the variables or the elements in the sequence data types like list, tuple, string, etc.
Deleting the variable reference.
Code:
Python Code
x = 3
y = 5
del x
print(y)
print(x)
Output:
5
Traceback (most recent call last):
File “c:\Users\angaj\Desktop\tuf codes\python_data_types.py”, line 5, in <module>
print(x)
NameError: name ‘x’ is not defined
Explanation: We can see that the interpreter is not able to identify the variable x, because it is deleted from the memory.
Deleting the element from the list
Code:
Python Code
l = [1, 2, 3, 4, 5, 6]
print("list before deletion")
print(l)
del l[2]
print("list After deletion")
print(l)
Output:
list before deletion
[1, 2, 3, 4, 5, 6]
list After deletion
[1, 2, 4, 5, 6]
Explanation: We can observe that the element at 2nd Position,i.e 3 is deleted from list.
If, else,elif :
They are used for decision-making.
Suppose there is a condition in if, if block is only executed When the condition is True. Suppose if we want to check for another condition then we use elif. elif is the short form of else if. else is used to execute a block when all the if and elif conditions are False.
Code:
Python Code
def check(s):
if s == "striver":
print("The string is striver")
elif s == "tuf":
print("The string is tuf")
else:
print("string is Someother")
check("striver")
check("tuf")
check("India")
Output:
The string is striver
The string is tuf
string is Someother
Explanation: In the 1st function call if block is executed, in the 2nd function call elif block is executed, and in the 3rd function call else block is executed.
- try,except,raise:
These are used for handling exceptions in Python. Exceptions are errors that suggest something went wrong while executing the program. Suppose if we are doubt at some point in code, that it may raise an error, then we can use try-except to handle the situation when the error occurs.
In except we can raise the error explicitly by checking the input.
Code:
Python Code
def Divide(a, b):
try:
c = a/b
except:
print("Division by zero")
return
return c
print(Divide(3, 2))
print(Divide(3, 0))
Output:
1.5
Division by zero
None
Explanation: The function Divide returns the value when a is divided by b. In the 1st function call, a is 3 and b is 2 when the function is called then control goes to try block and checks whether a/b is possible or not, as 3/2 is valid it returns the result i.e 1.5.
In the 2nd function call, a is 3 and b is 0, In the try statement Divison checked, as 3/0 is not possible, control goes to except statement and prints the Division by zero, and returns None.
- finally:
finally is used with try-except block. finally block is executed even if there is an error or not. That means finally block executes always.
Code:
Python Code
def Divide(a, b):
try:
c = a/b
except:
print("Division by zero")
return
finally:
print("Inside finally block")
return c
print(Divide(3, 2))
print(Divide(3, 0))
Output:
Inside finally block
1.5
Division by zero
Inside finally block
None
Explanation: In the 1st function call there is no error, In the 2nd call there is an error. The statement “Inside final block” is printed twice. That means finally the block is executed for both the function calls. This tells that finally block is executed when there is an error or no error.
- for:
for is used for looping. For loop is used when we know the number of times we need to iterate.
Code:
Python Code
l = [1, 2, 3, 4, 5]
for val in l:
print(val, end=" ")
Output :
1 2 3 4 5
- while:
while is also used for looping. Generally, a while loop is used to iterate until the condition is valid.
Code:
Python Code
a = 3
while a < 8:
print(a, end=" ")
a += 1
Output :
3 4 5 6 7
- from ,import
import keyword is used to import the modules into the current program. from is used to import specific attributes, and functions of modules into the current program.
Code:
Python Code
import sys
from math import gcd
print("gcd of 24,3 is:", gcd(24, 3))
Output :
gcd of 24,3 is: 3
Explanation: Using import we imported the sys module and using from we imported the gcd function in the math module.
- global:
In python variables declared outside the function are global variables, which means they can be used anywhere in the program. So they need not be passed inside the function as an argument if we want to do operations with it.
The modifications made for the global variable inside the function don’t change its value. The changes will be confined to that function only. If you want that the changes made to the global variable in a function to reflect everywhere then we need to declare it as a global inside the function.
Code:
Python Code
a = 3 # global variable
#This prints the value of a
def show():
print(a)
def fun1() :
a = 6
def fun2() :
global a
a = 7
show()
fun1()
show()
fun2()
show()
Output :
3
3
7
Explanation: function show() prints the value of a. First, the value of a is printed by calling show(). In fun1() we are changing the value of a. After calling fun1, if we print the value of a which is still 3, which means the value is not changed. The change we have made is confined to the fun1 only, it doesn’t reflect globally.
In fun2() after declaring the a as global we changed the value. Now if we print the value, the value is changed. That means the change we made is reflected globally. Now the value of a is 7.
- in
in is used to check whether a variable or value is present in sequence data types like list, tuple, etc.
Code:
Python Code
l = [1, 2, 3, 4, 5]
print(2 in l)
print(10 in l)
Output :
True
False
- is:
is used to check whether two variables refer to the same object or not.
Code:
Python Code
a = 3
b = 4
c = a
print(a is c)
print(a is b)
Output :
True
False
- lambda:
lambda is used to create an anonymous function(function with no name).
It consists of an expression that is evaluated and returned. It is an inline function with no return statement.
Code:
Python Code
a = lambda a : a**3
for i in range(1, 4):
print(a(i))
Output:
1
8
27
- pass
pass in a null statement in python. Nothing happens when it is executed.
Code:
Python Code
for i in range(1, 5):
if i == 3:
pass
print(i)
Output:
1
2
3
4
Explanation: When i is 3 if the block gets executed. As there is a pass in if block, nothing happens, after execution of if block.
- return:
return is used inside a function to exit the function or return a value from the function.
Code:
Python Code
def fun1():
for i in range(1, 5):
if i == 3:
return
print(i)
def fun2(a, b):
return a + b
fun1()
print(fun2(2, 3))
Output:
1
2
5
Explanation: In fun1 when i is 3, it encounters the return statement, so the function execution stopped there. fun2 returning the sum of 2,3.
- yield:
It ends the function and returns a generator.
Code:
Python Code
def generator():
for i in range(6):
yield i+1
p = generator()
for val in p:
print(val)
Output:
1
2
3
4
5
6
Identifiers :
Identifiers are the names given to the classes, functions, variables, etc. It helps to identify the entity.
Rules for writing identifiers:
- Identifiers can be written with a combination of letters in lower case (a to z) or UpperCase (A to Z) or digits (0 to 9) or underscore (_).
- The identifier cannot start with a digit.
- Keywords cannot be used as identifiers
- Using special characters like !, @, # ,%, $ etc are not allowed.
Examples:
Tuf, take_u_forward, striver_79 are the valid identifiers. 1variable, [email protected], for, while etc are not valid identifiers.
Special thanks to SaiSri Angajala for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article