Showing posts with label Python keywords. Show all posts
Showing posts with label Python keywords. Show all posts

Python: Keywords

 Like any other programming language, Python also has some reserved keywords, which have particular function in a program with particular guidelines.

In other words Python has a set of keywords that are reserved words and cannot be used as variable names, function names, or any other identifiers:
There are 35 keywords available with Python 3.11. These are:


In coming version, some extra may be introduced or some present keywords may be removed. By writing the following statement into the coding window you can retrieve the collection of keywords anytime in the version you are working on.

# Python program to import keyword library
import keyword
# displaying the complete list using "kwlist()."
print("the set of keyword in this version is:")
print(keyword.kwlist)

Output: 

the set of keyword in this version 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', 'pass' 'raise', 'return', 'try', 'while', 'with', 'yield']

By calling help("keyword"), we can retrieve information about the mentioned keyword.
For example:
help("nonlocal")
 

Uses of Python keywords:
The Python keywords are categorised here on the basis of their similar uses. This enables to maintain the large collection of keywords easily.
Value keywords (True, False and None): True and False are boolean values and these are results of comparison operations where as None represents a null value.
True Keyword: It is a boolean value and one of the results of comparison operation. It is same as 1 where as False is same as 0.
Example: To show that the 7 is greater than 5.
print(7 > 5)

Run Python in your browser


Note: First click clear history button then click run button.
Change the numbers or comparison operator(>, <, ==) and check the value.
Some other examples that will return value as 'True' are:
print(3<6)
print(2 in [1,2,3])
print(5 is 5)
print(4==4)
print(5==5 or 6==7)
print(5==5) and (8==8)
print("Hello" is not "Goodbye")
print(not(5==7))
print(4 not in [1, 2, 3])

Output:
True
True
True
True
True
True
True
True
True

You can try the programs in the code editor given above.

False Keyword: It is a boolean value and one of the results of comparison operation. It is same as 0.
Example: To show that the 7 is greater than 8.
print(7 > 8)

Output
False

Some other examples that will return value as 'False' are:
print(5>6)
print(4 in [1, 2, 3])
print("Hello" is "Goodbye")
print(5==6)
print(5==6) or (6==7)
print(5==6) and (6==7)
print("hello" is not "hello")
print(not(5 == 5))


Output:
False
False
False
False
False
False
False
False
False

None Keyword: None is not the same as 0, False, or an empty string. None is a data type of its own (Nonetype) and only None can be None. The None keyword is used to define a null value or no value at all.
Example:
x=None
print(x)

Output:
None

Other Example
print( None == 0 )
print( None == " " )
print( None == False )
A = None
B = None
print( A == B )

Output:
False
False
False
True

Operator Keywords (and, or, not, in, is): Many Python keywords are used as operators to perform mathematical operations. Find below a table to know how it is represented in other languages.

Python Keyword

Mathematical Operations

Operations in Other Languages

and

AND, ˄

&&

or

OR,  ˅

ІІ

not

NOT, ¬

!

in

CONTAINS, ϵ

 

is

IDENTITY

===


'and' keyword: The and keyword is a logical operator. Logical operators are used to combine conditional statements. If both side statements (left and right side of 'and' keyword) are true, it will return value as 'True' otherwise 'False'. If left side statement is X and right side statement is Y, then the values of X and Y in different conditions are:

X

Y

X and Y

True

True

True

True

False

False

False

True

False

False

False

False


Let's see an example:
x=(7>6 and 6>4)
print(x)

Output
True

'or' keyword: The or keyword in Python is used to check if, at minimum, one of the statements is true. If the first input is true, the or operator returns 'true', otherwise, it checks the second input. Find below the value of or keyword in different conditions.

X

Y

X or Y

True

True

True

True

False

True

False

True

True

False

False

False


'not' keyword: It is a logical operator. The return value will be true, if the statements are not true, otherwise it will return false.
Example:
x = False
print(not x)

Output
True

'in' keyword: The 'in' keyword is used for two purposes. First one to check if a value is present in a sequence(list, range, string etc) and second one to iterate through a sequence in a for loop.
Example:
fruits = "apple", "banana", "pineapple"
if "apple" in fruits:
print("yes")

Output
yes

Another example:
fruits = "apple", "banana", "pineapple"
for x in fruits:
print(x)

Output
apple
banana
pineapple

'is' keyword: The 'is' keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same objects and it returns False if the two objects are not same, even if both objects are 100% equal. The '==' operator is used to check, if two variables are equal.
Example to check if the two objects are the same object:

fruits = ["apple", "banana", "pineapple"]
x = fruits
print(x is fruits)

Output
True

Example to check the two objects are equal but not the same object:
a = ["apple", "banana", "pineapple"]
b = ["apple", "banana", "pineapple"]
print(a is b)

Output
False

The nonlocal Keyword: The nonlocal keyword is used to work with the variables in a function inside a function or in a nested functions, where the variable should not belong to the inner function. It is located in the outer function. We must define a non-local parameter with non-local keyword, if we need to change its value in a nested function.
Example of a function inside a function, which uses a variable x as a non local variable:
def the_outer_function():
x = 10
def the_inner_function():
nonlocal variable
x = 15
print("The value inside the inner function:",x)
the_inner_function()
print("The value inside the outer function:",x)
the_outer_function()

Output
The value inside the inner function: 15
The value inside the outer function: 15

Example without non local keyword:
def the_outer_function():
x = 10
def the_inner_function():
x = 15
print("The value inside the inner function:",x)
the_inner_function()
print("The value inside the outer function:",x)
the_outer_function()

Output
The value inside the inner function: 15
The value inside the outer function: 10

Iteration Keywords (for, while, break, continue): The iteration process is called looping is an essential programming fundamental. Python has multiple keywords to operate with loops. These would be utilised in almost every Python progam. To become a good Python developer, we should know their correct use.

The for keyword: The for loop is the most popular loop in Python. It is used by blending of two Python keywords. These are for and in.

The while keyword: Python's while loop works similar to other programming languages' while loops. The block after the while keyword is repeated repeatedly untill the condition following the while keyword become false. 

The break keyword: Break keyword is used to quickly break the loop. It is used for both 'for' and 'while' loops.

The continue keyword: Continue keyword like other programming languages' continue keyword used to jump to the subsequent loop. It quits performing the present loop and go to the subsequent one. 

# Program to show the use of keywords for, while, break, continue
for i in range(15):
print( i + 4, end = " ")
# breaking the loop when i = 9
if i == 9:
break
print()
# looping from 1 to 15
i = 0 # initial condition
while i < 15:
# When i has value 9, loop will jump to next iteration using continue. It will not print
if i == 9:
i += 3
continue
else:
# when i is not equal to 9, adding 2 and printing the value
print( i + 2, end = " ")
i += 1

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

Exception Handling Keywords (try, except, raise, finally, and assert): 
Try keyword: Try keyword is used to handle exceptions and is used in conjunction with the keyword except to handle problems in the program. When there is some kind of error, the program inside the try block is verified, but the code in that block is not executed.

Except keyword: As mentioned above, this keyword is used in conjunction with try keyword to solve the exceptions.

Finally keyword: Whatever the outcome of the try section, the 'finally' box is implemented every time.

Raise keyword: The raise keyword is used specifically to raise an exception.

Assert keyword: This keyword is used  to ensure that code is correct. If an expression is interpreted as true, nothing happens. If it is false, "AssertionError" is raised. An output with the error, followed by a comma, can also be printed.

# initializing the numbers
var1 = 5
var2 = 0
# Exception raised in the try section
try:
d = var1 // var2 # this will raise a "divide by zero" exception.
print( d )
# this section will handle exception raised in try block
except ZeroDivisionError:
print("We cannot divide by zero")
finally: # If exception is raised or not, this block will be executed every time
print("This is inside finally block")
# by using assert keyword we will check if var2 is 0
print ("The value of var1 / var2 is : ")
assert var2 != 0, "Divide by 0 error"
print (var1 / var2)

Output
We cannot divide by zero
This is inside finally block
The value of var1 / var2 is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [44], in ()
15 # by using assert keyword we will check if var2 is 0
16 print ("The value of var1 / var2 is : ")
---> 17 assert var2 != 0, "Divide by 0 error"
18 print (var1 / var2)
AssertionError: Divide by 0 error

Pass keyword: In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it runs, nothing occurs.
For exmple, we have a function that has not been coded yet however we wish to do so in the long term. If we write just this in the middle of code.
Syntax: 
def function_pass(arguments):

Output
def function_pass(arguments):
IndentationError: Expected an indented block after function definition on line 1

As shown, an indentation error will be thrown. Rather, we use the pass command to create a blank container.
def function_pass(arguments):
pass

We can use the pass keyword to create an empty class too.
Syntax:
class passed_class:
pass

Return Keyword:The return keyword is used to leave a function and return a result. By default 'none' keyword is returned if we don't specifically return a value. 
Let's see the example:
def func_with_return():
var = 50
return var
def func_with_no_return():
var = 100
print( func_with_return() )
print( func_with_no_return() )
Output
50
None

Del Keyword:The del keyword is used to remove any reference to an object. In Python every entity is an object. We can use the del command to remove a variable reference. 
Let's see the example:
var1 = var2 = 5
del var1
print( var2 )
print( var1 )

Output
5 --------------------------------------------------------------------------- NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )
NameError: name 'var1' is not defined

In above example, we cxan notice that the variable var1's treference has been removed. As a result, it's no longer recognised. However var2 still exists.
Del keyword is also used to delete entries from a list or a dictionary.
Let's see another example:
list_ = ['A','B','C']
del list_[2]
print(list_)

Output
['A', 'B']

Python: Functions