0% found this document useful (0 votes)
2 views152 pages

Control Statements

This document is a comprehensive Python tutorial covering data type conversions, including converting strings to integers, floats, and vice versa using built-in functions like int(), float(), and str(). It also explains Python's support for Unicode and character encoding, as well as the concept of literals in Python, detailing various types of literals such as integer, float, complex, string, list, tuple, and dictionary literals. Additionally, it provides examples of how to use these functions and concepts in practice.

Uploaded by

Sanjiv Regmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views152 pages

Control Statements

This document is a comprehensive Python tutorial covering data type conversions, including converting strings to integers, floats, and vice versa using built-in functions like int(), float(), and str(). It also explains Python's support for Unicode and character encoding, as well as the concept of literals in Python, detailing various types of literals such as integer, float, complex, string, list, tuple, and dictionary literals. Additionally, it provides examples of how to use these functions and concepts in practice.

Uploaded by

Sanjiv Regmi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Tutorial

<<< a
1
<<< type(a)
<class 'int'>

String to Integer
The int() function returns an integer from a string object, only if it contains a valid integer
representation.

<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>

However, if the string contains a non-integer representation, Python raises ValueError.

<<< a = int("10.5")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
<<< a = int("Hello World")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello World'

The int() function also returns integer from binary, octal and hexa-decimal string. For this,
the function needs a base parameter which must be 2, 8 or 16 respectively. The string
should have a valid binary/octal/Hexa-decimal representation.

Binary String to Integer


The string should be made up of 1 and 0 only, and the base should be 2.

<<< a = int("110011", 2)
<<< a

77
Python Tutorial

51

The Decimal equivalent of binary number 110011 is 51.

Octal String to Integer


The string should only contain 0 to 7 digits, and the base should be 8.

<<< a = int("20", 8)
<<< a
16

The Decimal equivalent of octal 20 is 16.

Hexa-Decimal String to Integer


The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F.
Base should be 16.

<<< a = int("2A9", 16)


<<< a
681

Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions
with calculator app in Windows, Ubuntu or Smartphones.
Following is an example to convert number, float and string into integer data type:

a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3

print (a)
print (b)
print (c)

This will produce the following result −

1
2
3

Python float() Function


The float() is a built-in function in Python. It returns a float object if the argument is a
float literal, integer or a string with valid floating point representation.
Using float() with an float object as argument is equivalent to declaring a float object
directly

<<< a = float(9.99)

78
Python Tutorial

<<< a
9.99
<<< type(a)
<class 'float'>

is same as −

<<< a = 9.99
<<< a
9.99
<<< type(a)
<class 'float'>

If the argument to float() function is an integer, the returned value is a floating point with
fractional part set to 0.

<<< a = float(100)
<<< a
100.0
<<< type(a)
<class 'float'>

The float() function returns float object from a string, if the string contains a valid floating
point number, otherwise ValueError is raised.

<<< a = float("9.99")
<<< a
9.99
<<< type(a)
<class 'float'>
<<< a = float("1,234.50")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'

The reason of ValueError here is the presence of comma in the string.


For the purpose of string to float conversion, the scientific notation of floating point is also
considered valid.

<<< a = float("1.00E4")
<<< a
10000.0
<<< type(a)

79
Python Tutorial

<class 'float'>
<<< a = float("1.00E-4")
<<< a
0.0001
<<< type(a)
<class 'float'>

Following is an example to convert number, float and string into float data type:

a = float(1) # a will be 1.0


b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

This will produce the following result −

1.0
2.2
3.3

Python str() Function


We saw how a Python obtains integer or float number from corresponding string
representation. The str() function works the opposite. It surrounds an integer or a float
object with quotes (') to return a str object. The str() function returns the string
representation of any Python object. In this section, we shall see different examples of
str() function in Python.
The str() function has three parameters. First required parameter (or argument) is the
object whose string representation we want. Other two operators, encoding and errors,
are optional.
We shall execute str() function in Python console to easily verify that the returned object
is a string, with the enclosing quotation marks (').

Integer to string
You can convert any integer number into a string as follows:

<<< a = str(10)
<<< a
'10'
<<< type(a)
<class 'str'>

80
Python Tutorial

Float to String
The str() function converts floating point objects with both the notations of floating point,
standard notation with a decimal point separating integer and fractional part, and the
scientific notation to string object.

<<< a=str(11.10)
<<< a
'11.1'
<<< type(a)
<class 'str'>
<<< a = str(2/5)
<<< a
'0.4'
<<< type(a)
<class 'str'>

In the second case, a division expression is given as argument to str() function. Note that
the expression is evaluated first and then result is converted to string.
Floating points in scientific notations using E or e and with positive or negative power are
converted to string with str() function.

<<< a=str(10E4)
<<< a
'100000.0'
<<< type(a)
<class 'str'>
<<< a=str(1.23e-4)
<<< a
'0.000123'
<<< type(a)
<class 'str'>

When Boolean constant is entered as argument, it is surrounded by (') so that True


becomes 'True'. List and Tuple objects can also be given argument to str() function. The
resultant string is the list/tuple surrounded by (').

<<< a=str('True')
<<< a
'True'
<<< a=str([1,2,3])
<<< a
'[1, 2, 3]'

81
Python Tutorial

<<< a=str((1,2,3))
<<< a
'(1, 2, 3)'
<<< a=str({1:100, 2:200, 3:300})
<<< a
'{1: 100, 2: 200, 3: 300}'

Following is an example to convert number, float and string into string data type:

a = str(1) # a will be "1"


b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

This will produce the following result −

1
2.2
3.3

Conversion of Sequence Types


List, Tuple and String are Python's sequence types. They are ordered or indexed collection
of items.
A string and tuple can be converted into a list object by using the list() function. Similarly,
the tuple() function converts a string or list to a tuple.
We shall take an object of each of these three sequence types and study their inter-
conversion.

<<< a=[1,2,3,4,5] # List Object


<<< b=(1,2,3,4,5) # Tuple Object
<<< c="Hello" # String Object

### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']

### The parentheses of tuple are replaced by square brackets

82
Python Tutorial

<<< obj=list(b)
<<< obj
[1, 2, 3, 4, 5]

### tuple() separates each character from string and builds a tuple of
characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')

### square brackets of list are replaced by parentheses.


<<< obj=tuple(a)
<<< obj
(1, 2, 3, 4, 5)

### str() function puts the list and tuple inside the quote symbols.
<<< obj=str(a)
<<< obj
'[1, 2, 3, 4, 5]'

<<< obj=str(b)
<<< obj
'(1, 2, 3, 4, 5)'

Thus Python's explicit type casting feature allows conversion of one data type to other with
the help of its built-in functions.

Data Type Conversion Functions


There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

[Link]. Function & Description


Python int() function
1
Converts x to an integer. base specifies the base if x is a string.

Python long() function

2 Converts x to a long integer. base specifies the base if x is a string. This


function has been deprecated.

3 Python float() function

83
Python Tutorial

Converts x to a floating-point number.

Python complex() function


4
Creates a complex number.
Python str() function
5
Converts object x to a string representation.

Python repr() function


6
Converts object x to an expression string.

Python eval() function


7
Evaluates a string and returns an object.

Python tuple() function


8
Converts s to a tuple.
Python list() function
9
Converts s to a list.
Python set() function
10
Converts s to a set.
Python dict() function
11
Creates a dictionary. d must be a sequence of (key,value) tuples.

Python frozenset() function


12
Converts s to a frozen set.
Python chr() function
13
Converts an integer to a character.
Python unichr() function
14
Converts an integer to a Unicode character.

Python ord() function


15
Converts a single character to its integer value.

Python hex() function


16
Converts an integer to a hexadecimal string.

Python oct() function


17
Converts an integer to an octal string.

84
14. Python - Unicode System Python Tutorial

What is Unicode System?


Software applications often require to display messages output in a variety in different
languages such as in English, French, Japanese, Hebrew, or Hindi. Python's string type
uses the Unicode Standard for representing characters. It makes the program possible to
work with all these different possible characters.
A character is the smallest possible component of a text. 'A', 'B', 'C', etc., are all different
characters. So are 'È' and 'Í'. A unicode string is a sequence of code points, which are
numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points
needs to be represented in memory as a set of code units, and code units are then mapped
to 8-bit bytes.

Character Encoding
A sequence of code points is represented in memory as a set of code units, mapped to 8-
bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a
character encoding.
Three types of encodings are present, UTF-8, UTF-16 and UTF-32. UTF stands for Unicode
Transformation Format.

Python's Unicode Support


Python 3.0 onwards has built-in support for Unicode. The str type contains Unicode
characters, hence any string created using single, double or the triple-quoted string syntax
is stored as Unicode. The default encoding for Python source code is UTF-8.
Hence, string may contain literal representation of a Unicode character (3/4) or its Unicode
value (\u00BE).

Example

var = "3/4"
print (var)
var = "\u00BE"
print (var)

This above code will produce the following output −

3/4
¾

Example
In the following example, a string '10' is stored using the Unicode values of 1 and 0 which
are \u0031 and u0030 respectively.

85
Python Tutorial

var = "\u0031\u0030"
print (var)

It will produce the following output −

10

Strings display the text in a human-readable format, and bytes store the characters as
binary data. Encoding converts data from a character string to a series of bytes. Decoding
translates the bytes back to human-readable characters and symbols. It is important not
to confuse these two methods. Encode is a string method, while decode is a method of the
Python byte object.

Example
In the following example, we have a string variable that consists of ASCII characters.
ASCII is a subset of Unicode character set. The encode() method is used to convert it into
a bytes object.

string = "Hello"
tobytes = [Link]('utf-8')
print (tobytes)
string = [Link]('utf-8')
print (string)

The decode() method converts byte object back to the str object. The encoding method
used is utf-8.

b'Hello'
Hello

Example
In the following example, the Rupee symbol (₹) is stored in the variable using its Unicode
value. We convert the string to bytes and back to str.

string = "\u20B9"
print (string)
tobytes = [Link]('utf-8')
print (tobytes)
string = [Link]('utf-8')
print (string)

When you execute the above code, it will produce the following output −


b'\xe2\x82\xb9'

86
Python Tutorial

87
15. Python - Literals Python Tutorial

What are Python Literals?


Python literals or constants are the notation for representing a fixed value in source code.
In contrast to variables, literals (123, 4.3, "Hello") are static values or you can say
constants which do not change throughout the operation of the program or application.
For example, in the following assignment statement:

x = 10

Here 10 is a literal as numeric value representing 10, which is directly stored in memory.
However,

y = x*2

Here, even if the expression evaluates to 20, it is not literally included in source code. You
can also declare an int object with built-in int() function. However, this is also an indirect
way of instantiation and not with literal.

x = int(10)

Different Types of Python Literals


Python provides following literals which will be explained in this tutorial:
 Integer Literal
 Float Literal
 Complex Literal
 String Literal
 List Literal
 Tuple Literal
 Dictionary Literal

Python Integer Literal


Any representation involving only the digit symbols (0 to 9) creates an object of int type.
The object so declared may be referred by a variable using an assignment operator.
Integer literals consist three different types of different literal values decimal, octal, and
hexadecimal literals.

1. Decimal Literal
Decimal literals represent the signed or unsigned numbers. Digitals from 0 to 9 are used
to create a decimal literal value.
Look at the below statement assigning decimal literal to the variable −

x = 10
y = -25

88
Python Tutorial

z = 0

2. Octal Literal
Python allows an integer to be represented as an octal number or a hexadecimal number.
A numeric representation with only eight digit symbols (0 to 7) but prefixed by 0o or 0O
is an octal number in Python.
Look at the below statement assigning octal literal to the variable −

x = 0O34

3. Hexadecimal Literal
Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or 0X
represents an integer in Hexadecimal form in Python.
Look at the below statement assigning hexadecimal literal to the variable −

x = 0X1C

However, it may be noted that, even if you use octal or hexadecimal literal notation,
Python internally treats them as of int type.
Example

# Using Octal notation


x = 0O34
print ("0O34 in octal is", x, type(x))
# Using Hexadecimal notation
x = 0X1c
print ("0X1c in Hexadecimal is", x, type(x))

When you run this code, it will produce the following output −

0O34 in octal is 28 <class 'int'>


0X1c in Hexadecimal is 28 <class 'int'>

Python Float Literal


A floating point number consists of an integral part and a fractional part. Conventionally,
a decimal point symbol (.) separates these two parts in a literal representation of a float.
For example,
Example of Float Literal

x = 25.55
y = 0.05
z = -12.2345

For a floating point number which is too large or too small, where number of digits before
or after decimal point is more, a scientific notation is used for a compact literal

89
Python Tutorial

representation. The symbol E or e followed by positive or negative integer, follows after


the integer part.
Example of Float Scientific Notation Literal
For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2 is
equivalent to 0.0123

# Using normal floating point notation


x = 1.23
print ("1.23 in normal float literal is", x, type(x))
# Using Scientific notation
x = 1.23E5
print ("1.23E5 in scientific notation is", x, type(x))
x = 1.23E-2
print ("1.23E-2 in scientific notation is", x, type(x))

Here, you will get the following output −

1.23 in normal float literal is 1.23 <class 'float'>


1.23E5 in scientific notation is 123000.0 <class 'float''>
1.23E-2 in scientific notation is 0.0123 <class 'float''>

Python Complex Literal


A complex number comprises of a real and imaginary component. The imaginary
component is any number (integer or floating point) multiplied by square root of "-1"

(√ −1). In literal representation (√-1) is representation by "j" or "J". Hence, a literal


representation of a complex number takes a form x+yj.
Example of Complex Type Literal

#Using literal notation of complex number


x = 2+3j
print ("2+3j complex literal is", x, type(x))
y = 2.5+4.6j
print ("2.5+4.6j complex literal is", x, type(x))

This code will produce the following output −

2+3j complex literal is (2+3j) <class 'complex'>


2.5+4.6j complex literal is (2+3j) <class 'complex'>

Python String Literal


A string object is one of the sequence data types in Python. It is an immutable sequence
of Unicode code points. Code point is a number corresponding to a character according to
Unicode standard. Strings are objects of Python's built-in class 'str'.
90
Python Tutorial

String literals are written by enclosing a sequence of characters in single quotes ('hello'),
double quotes ("hello") or triple quotes ('''hello''' or """hello""").
Example of String Literal

var1='hello'
print ("'hello' in single quotes is:", var1, type(var1))
var2="hello"
print ('"hello" in double quotes is:', var1, type(var1))
var3='''hello'''
print ("''''hello'''' in triple quotes is:", var1, type(var1))
var4="""hello"""
print ('"""hello""" in triple quotes is:', var1, type(var1))

Here, you will get the following output −

'hello' in single quotes is: hello <class 'str'>


"hello" in double quotes is: hello <class 'str'>
''''hello'''' in triple quotes is: hello <class 'str'>
"""hello""" in triple quotes is: hello <class 'str'>

Example of String Literal with Double Quotes Inside String


If it is required to embed double quotes as a part of string, the string itself should be put
in single quotes. On the other hand, if single quoted text is to be embedded, string should
be written in double quotes.

var1='Welcome to "Python Tutorial" from TutorialsPoint'


print (var1)
var2="Welcome to 'Python Tutorial' from TutorialsPoint"
print (var2)

It will produce the following output −

Welcome to "Python Tutorial" from TutorialsPoint


Welcome to 'Python Tutorial' from TutorialsPoint

Python List Literal


List object in Python is a collection of objects of other data type. List is an ordered collection
of items not necessarily of same type. Individual object in the collection is accessed by
index starting with zero.
Literal representation of a list object is done with one or more items which are separated
by comma and enclosed in square brackets [].
Example of List Type Literal

L1=[1,"Ravi",75.50, True]

91
Python Tutorial

print (L1, type(L1))

It will produce the following output −

[1, 'Ravi', 75.5, True] <class 'list'>

Python Tuple Literal


Tuple object in Python is a collection of objects of other data type. Tuple is an ordered
collection of items not necessarily of same type. Individual object in the collection is
accessed by index starting with zero.
Literal representation of a tuple object is done with one or more items which are separated
by comma and enclosed in parentheses ().
Example of Tuple Type Literal

T1=(1,"Ravi",75.50, True)
print (T1, type(T1))

It will produce the following output −

[1, 'Ravi', 75.5, True] <class tuple>

Example of Tuple Type Literal Without Parenthesis


Default delimiter for Python sequence is parentheses, which means a comma separated
sequence without parentheses also amounts to declaration of a tuple.

T1=1,"Ravi",75.50, True
print (T1, type(T1))

Here too, you will get the same output −

[1, 'Ravi', 75.5, True] <class tuple>

Python Dictionary Literal


Like list or tuple, dictionary is also a collection data type. However, it is not a sequence.
It is an unordered collection of items, each of which is a key-value pair. Value is bound to
key by the ":" symbol. One or more key:value pairs separated by comma are put inside
curly brackets to form a dictionary object.
Example of Dictionary Type Literal

capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo",


"India":"New Delhi"}
numbers={1:"one", 2:"Two", 3:"three",4:"four"}
points={"p1":(10,10), "p2":(20,20)}

print (capitals, type(capitals))


print (numbers, type(numbers))

92
Python Tutorial

print (points, type(points))

Key should be an immutable object. Number, string or tuple can be used as key. Key
cannot appear more than once in one collection. If a key appears more than once, only
the last one will be retained. Values can be of any data type. One value can be assigned
to more than one keys. For example,

staff={"Krishna":"Officer", "Rajesh":"Manager", "Ragini":"officer",


"Anil":"Clerk", "Kavita":"Manager"}

93
16. Python - Operators Python Tutorial

Python Operators
Python operators are special symbols used to perform specific operations on one or more
operands. The variables, values, or expressions can be used as operands. For example,
Python's addition operator (+) is used to perform addition operations on two variables,
values, or expressions.
The following are some of the terms related to Python operators:
 Unary operators: Python operators that require one operand to perform a specific
operation are known as unary operators.
 Binary operators: Python operators that require two operands to perform a
specific operation are known as binary operators.
 Operands: Variables, values, or expressions that are used with the operator to
perform a specific operation are known as operands.

Types of Python Operators


Python operators are divided in the following categories −
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look at all the operators one by one.

Python Arithmetic Operators


Python Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, etc.
The following table contains all arithmetic operators with their symbols, names, and
examples (assume that the values of a and b are 10 and 20, respectively) −

Operator Name Example


+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

94
Python Tutorial

Example of Python Arithmetic Operators

a = 21
b = 10
c = 0

c = a + b
print ("a: {} b: {} a+b: {}".format(a,b,c))

c = a - b
print ("a: {} b: {} a-b: {}".format(a,b,c) )

c = a * b
print ("a: {} b: {} a*b: {}".format(a,b,c))

c = a / b
print ("a: {} b: {} a/b: {}".format(a,b,c))

c = a % b
print ("a: {} b: {} a%b: {}".format(a,b,c))

a = 2
b = 3
c = a**b
print ("a: {} b: {} a**b: {}".format(a,b,c))

a = 10
b = 5
c = a//b
print ("a: {} b: {} a//b: {}".format(a,b,c))

Output

a: 21 b: 10 a+b: 31
a: 21 b: 10 a-b: 11
a: 21 b: 10 a*b: 210
a: 21 b: 10 a/b: 2.1

95
Python Tutorial

a: 21 b: 10 a%b: 1
a: 2 b: 3 a**b: 8
a: 10 b: 5 a//b: 2

Python Comparison Operators


Python comparison operators compare the values on either side of them and decide the
relation among them. They are also called Relational operators.
The following table contains all comparison operators with their symbols, names, and
examples (assume that the values of a and b are 10 and 20, respectively) −

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.


> Greater than (a > b) is not true.
< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.

Example of Python Comparison Operators

a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")

if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")

if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")

if ( a > b ):

96
Python Tutorial

print ("Line 4 - a is greater than b")


else:
print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")

Output

Line 1 - a is not equal to b


Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b
Line 5 - a is either less than or equal to b
Line 6 - b is either greater than or equal to b

Python Assignment Operators


Python Assignment operators are used to assign values to variables. Following is a table
which shows all Python assignment operators.
The following table contains all assignment operators with their symbols, names, and
examples −

Operator Example Same As


= a = 10 a = 10
+= a += 30 a = a + 30
-= a -= 15 a = a - 15
*= a *= 10 a = a * 10
/= a /= 5 a=a/5
%= a %= 5 a=a%5
**= a **= 4 a = a ** 4
//= a //= 5 a = a // 5
&= a &= 5 a=a&5

97
Python Tutorial

|= a |= 5 a=a|5
^= a ^= 5 a=a^5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5

Example of Python Assignment Operators

a = 21
b = 10
c = 0
print ("a: {} b: {} c : {}".format(a,b,c))
c = a + b
print ("a: {} c = a + b: {}".format(a,c))

c += a
print ("a: {} c += a: {}".format(a,c))

c *= a
print ("a: {} c *= a: {}".format(a,c))

c /= a
print ("a: {} c /= a : {}".format(a,c))

c = 2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))

c **= a
print ("a: {} c **= a: {}".format(a,c))

c //= a
print ("a: {} c //= a: {}".format(a,c))

Output

a: 21 b: 10 c: 0
a: 21 c = a + b: 31
a: 21 c += a: 52
a: 21 c *= a: 1092

98
Python Tutorial

a: 21 c /= a : 52.0
a: 21 b: 10 c : 2
a: 21 c %= a: 2
a: 21 c **= a: 2097152
a: 21 c //= a: 99864

Python Bitwise Operators


Python bitwise operator works on bits and performs bit by bit operation. These operators
are used to compare binary numbers.
The following table contains all bitwise operators with their symbols, names, and examples

Operator Name Example


& AND a&b
| OR a|b
^ XOR a^b
~ NOT ~a
<< Zero fill left shift a << 3
>> Signed right shift a >> 3

Example of Python Bitwise Operators

a = 20
b = 10

print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0

c = a & b;
print ("result of AND is ", c,':',bin(c))

c = a | b;
print ("result of OR is ", c,':',bin(c))

c = a ^ b;
print ("result of EXOR is ", c,':',bin(c))

c = ~a;
print ("result of COMPLEMENT is ", c,':',bin(c))

99
Python Tutorial

c = a << 2;
print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Output

a= 20 : 0b10100 b= 10 : 0b1010
result of AND is 0 : 0b0
result of OR is 30 : 0b11110
result of EXOR is 30 : 0b11110
result of COMPLEMENT is -21 : -0b10101
result of LEFT SHIFT is 80 : 0b1010000
result of RIGHT SHIFT is 5 : 0b101

Python Logical Operators


Python logical operators are used to combine two or more conditions and check the final
result.
The following table contains all logical operators with their symbols, names, and examples

Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)

Example of Python Logical Operators

var = 5

print(var > 3 and var < 10)


print(var > 3 or var < 4)
print(not (var > 3 and var < 10))

Output

True
True
False

Python Membership Operators

100
Python Tutorial

Python's membership operators test for membership in a sequence, such as strings, lists,
or tuples.
There are two membership operators as explained below −

Operator Description Example

Returns True if it finds a


in variable in the specified a in b
sequence, false otherwise.

returns True if it does not finds


not in a variable in the specified a not in b
sequence and false otherwise.

Example of Python Membership Operators

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

print ("a:", a, "b:", b, "list:", list)

if ( a in list ):
print ("a is present in the given list")
else:
print ("a is not present in the given list")

if ( b not in list ):
print ("b is not present in the given list")
else:
print ("b is present in the given list")

c=b/a
print ("c:", c, "list:", list)
if ( c in list ):
print ("c is available in the given list")
else:
print ("c is not available in the given list")

Output

101
Python Tutorial

a: 10 b: 20 list: [1, 2, 3, 4, 5]
a is not present in the given list
b is not present in the given list
c: 2.0 list: [1, 2, 3, 4, 5]
c is available in the given list

Python Identity Operators


Python identity operators compare the memory locations of two objects.
There are two Identity operators explained below −

Operator Description Example

Returns True if both


is variables are the same a is b
object and false otherwise.

Returns True if both


is not variables are not the same a is not b
object and false otherwise.

Example of Python Identity Operators

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

print(a is c)
print(a is b)

print(a is not c)
print(a is not b)

Output

True
False
False
True

102
Python Tutorial

Python Operators Precedence


Operators precedence decides the order of the evaluation in which an operator is
evaluated. Python operators have different levels of precedence. The following table
contains the list of operators having highest to lowest precedence −
The following table lists all operators from highest precedence to lowest.

[Link]. Operator & Description


**
1
Exponentiation (raise to the power)
~+-

2 Complement, unary plus and minus


(method names for the last two are +@
and -@)
* / % //
3 Multiply, divide, modulo and floor
division
+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'

<= < > >=


8
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
Read more about the Python operators precedence here: Python operators precedence

103
17. Python - Arithmetic OperatorsPython Tutorial

Python Arithmetic Operators


Python arithmetic operators are used to perform mathematical operations such as
addition, subtraction, multiplication, division, and more on numbers. Arithmetic operators
are binary operators in the sense they operate on two operands. Python fully supports
mixed arithmetic. That is, the two operands can be of two different number types. In such
a situation.

Types of Arithmetic Operators


Following is the table which lists down all the arithmetic operators available in Python:

Operator Name Example


+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

Let us study these operators with examples.

Addition Operator
The addition operator is represented by the + symbol. It is a basic arithmetic operator. It
adds the two numeric operands on the either side and returns the addition result.
Example to add two integer numbers
In the following example, the two integer variables are the operands for the "+" operator.

a=10
b=20
print ("Addition of two integers")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

Addition of two integers


a = 10 b = 20 addition = 30

Example to add integer and float numbers


Addition of integer and float results in a float.

104
Python Tutorial

a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

Addition of integer and float


a = 10 b = 20.5 addition = 30.5

Example to add two complex numbers


The result of adding float to complex is a complex number.

a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)

It will produce the following output −

Addition of complex and float


a= (10+5j) b= 20.5 addition= (30.5+5j)

Subtraction Operator
The subtraction operator is represented by the - symbol. It subtracts the second operand
from the first. The resultant number is negative if the second operand is larger.
Example to subtract two integer numbers
First example shows subtraction of two integers.

a=10
b=20
print ("Subtraction of two integers:")
print ("a =",a,"b =",b,"a-b =",a-b)
print ("a =",a,"b =",b,"b-a =",b-a)

Result −

Subtraction of two integers


a = 10 b = 20 a-b = -10
a = 10 b = 20 b-a = 10

Example to subtract integer and float numbers


Subtraction of an integer and a float follows the same principle.

a=10

105
Python Tutorial

b=20.5
print ("subtraction of integer and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

subtraction of integer and float


a= 10 b= 20.5 a-b= -10.5
a= 10 b= 20.5 b-a= 10.5

Example to subtract complex numbers


In the subtraction involving a complex and a float, real component is involved in the
operation.

a=10+5j
b=20.5
print ("subtraction of complex and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

subtraction of complex and float


a= (10+5j) b= 20.5 a-b= (-10.5+5j)
a= (10+5j) b= 20.5 b-a= (10.5-5j)

Multiplication Operator
The * (asterisk) symbol is defined as multiplication operator in Python (as in many
languages). It returns the product of the two operands on its either side. If any of the
operands negative, the result is also negative. If both are negative, the result is positive.
Changing the order of operands doesn't change the result
Example to multiply two integers

a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of two integers


a = 10 b = 20 a*b = 200

Example to multiply integer and float numbers

106
Python Tutorial

In multiplication, a float operand may have a standard decimal point notation, or a


scientific notation.

a=10
b=20.5
print ("Multiplication of integer and float")
print ("a=",a,"b=",b,"a*b=",a*b)

a=-5.55
b=6.75E-3
print ("Multiplication of float and float")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of integer and float


a = 10 b = 20.5 a-b = -10.5
Multiplication of float and float
a = -5.55 b = 0.00675 a*b = -0.037462499999999996

Example to multiply complex numbers


For the multiplication operation involving one complex operand, the other operand
multiplies both the real part and imaginary part.

a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of complex and float


a = (10+5j) b = 20.5 a*b = (205+102.5j)

Division Operator
The "/" symbol is usually called as forward slash. The result of division operator is
numerator (left operand) divided by denominator (right operand). The resultant number
is negative if any of the operands is negative. Since infinity cannot be stored in the
memory, Python raises ZeroDivisionError if the denominator is 0.
The result of division operator in Python is always a float, even if both operands are
integers.
Example to divide two numbers

a=10
b=20

107
Python Tutorial

print ("Division of two integers")


print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

Division of two integers


a= 10 b= 20 a/b= 0.5
a= 10 b= 20 b/a= 2.0

Example to divide two float numbers


In Division, a float operand may have a standard decimal point notation, or a scientific
notation.

a=10
b=-20.5
print ("Division of integer and float")
print ("a=",a,"b=",b,"a/b=",a/b)
a=-2.50
b=1.25E2
print ("Division of float and float")
print ("a=",a,"b=",b,"a/b=",a/b)

It will produce the following output −

Division of integer and float


a= 10 b= -20.5 a/b= -0.4878048780487805
Division of float and float
a= -2.5 b= 125.0 a/b= -0.02

Example to divide complex numbers


When one of the operands is a complex number, division between the other operand and
both parts of complex number (real and imaginary) object takes place.

a=7.5+7.5j
b=2.5
print ("Division of complex and float")
print ("a =",a,"b =",b,"a/b =",a/b)
print ("a =",a,"b =",b,"b/a =",b/a)

It will produce the following output −

Division of complex and float


a = (7.5+7.5j) b = 2.5 a/b = (3+3j)

108
Python Tutorial

a = (7.5+7.5j) b = 2.5 b/a = (0.16666666666666666-0.16666666666666666j)

If the numerator is 0, the result of division is always 0 except when denominator is 0, in


which case, Python raises ZeroDivisionError wirh Division by Zero error message.

a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

a= 0 b= 2.5 a/b= 0.0


Traceback (most recent call last):
File "C:\Users\mlath\examples\[Link]", line 20, in <module>
print ("a=",a,"b=",b,"b/a=",b/a)
~^~
ZeroDivisionError: float division by zero

Modulus Operator
Python defines the "%" symbol, which is known aa Percent symbol, as Modulus (or modulo)
operator. It returns the remainder after the denominator divides the numerator. It can
also be called Remainder operator. The result of the modulus operator is the number that
remains after the integer quotient. To give an example, when 10 is divided by 3, the
quotient is 3 and remainder is 1. Hence, 10%3 (normally pronounced as 10 mod 3) results
in 1.
Example for modulus operation on integers
If both the operands are integers, the modulus value is an integer. If numerator is
completely divisible, remainder is 0. If numerator is smaller than denominator, modulus
is equal to the numerator. If denominator is 0, Python raises ZeroDivisionError.

a=10
b=2
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=4
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=",a, "b=",b, "b%a=", b%a)
a=0
b=10
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=", a, "b=", b, "b%a=",b%a)

109
Python Tutorial

It will produce the following output −

a= 10 b= 2 a%b= 0
a= 10 b= 4 a%b= 2
a= 10 b= 4 b%a= 4
a= 0 b= 10 a%b= 0
Traceback (most recent call last):
File "C:\Users\mlath\examples\[Link]", line 13, in <module>
print ("a=", a, "b=", b, "b%a=",b%a)
~^~
ZeroDivisionError: integer modulo by zero

Example for modulus operation on floats


If any of the operands is a float, the mod value is always float.

a=10
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=1.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=7.7
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=12.4
b=3
print ("a=",a, "b=",b, "a%b=", a%b)

It will produce the following output −

a= 10 b= 2.5 a%b= 0.0


a= 10 b= 1.5 a%b= 1.0
a= 7.7 b= 2.5 a%b= 0.20000000000000018
a= 12.4 b= 3 a%b= 0.40000000000000036

Python doesn't accept complex numbers to be used as operand in modulus operation. It


throws TypeError: unsupported operand type(s) for %.

Exponent Operator
Python uses ** (double asterisk) as the exponent operator (sometimes called raised to
operator). So, for a**b, you say a raised to b, or even bth power of a.

110
Python Tutorial

If in the exponentiation expression, both operands are integer, result is also an integer.
In case either one is a float, the result is float. Similarly, if either one operand is complex
number, exponent operator returns a complex number.
If the base is 0, the result is 0, and if the index is 0 then the result is always 1.
Example of exponent operator

a=10
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=10
b=1.5
print ("a=",a, "b=",b, "a**b=", a**b)
a=7.7
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=1+2j
b=4
print ("a=",a, "b=",b, "a**b=", a**b)
a=12.4
b=0
print ("a=",a, "b=",b, "a**b=", a**b)
print ("a=",a, "b=",b, "b**a=", b**a)

It will produce the following output −

a= 10 b= 2 a**b= 100
a= 10 b= 1.5 a**b= 31.622776601683793
a= 7.7 b= 2 a**b= 59.290000000000006
a= (1+2j) b= 4 a**b= (-7-24j)
a= 12.4 b= 0 a**b= 1.0
a= 12.4 b= 0 b**a= 0.0

Floor Division Operator


Floor division is also called as integer division. Python uses // (double forward slash)
symbol for the purpose. Unlike the modulus or modulo which returns the remainder, the
floor division gives the quotient of the division of operands involved.
If both operands are positive, floor operator returns a number with fractional part removed
from it. For example, the floor division of 9.8 by 2 returns 4 (pure division is 4.9, strip the
fractional part, result is 4).

111
Python Tutorial

But if one of the operands is negative, the result is rounded away from zero (towards
negative infinity). Floor division of -9.8 by 2 returns 5 (pure division is -4.9, rounded away
from 0).
Example of floor division operator

a=9
b=2
print ("a=",a, "b=",b, "a//b=", a//b)
a=9
b=-2
print ("a=",a, "b=",b, "a//b=", a//b)
a=10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)
a=-10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)

It will produce the following output −

a= 9 b= 2 a//b= 4
a= 9 b= -2 a//b= -5
a= 10 b= 1.5 a//b= 6.0
a= -10 b= 1.5 a//b= -7.0

Precedence and Associativity of Arithmetic Operators


Operator(s) Description Associativity
Associativity of Exponent operator
** Exponent Operator
is from Right to Left.
Modulus, Associativity of Modulus,
Multiplication, Multiplication, Division, and Floor
%, *, /, //
Division, and Floor Division operators are from Left to
Division Right.
Addition and Associativity of Addition and
+, – Subtraction Subtraction operators are
Operators from Left to Right.

Arithmetic Operators with Complex Numbers


Arithmetic operators behave slightly differently when the both operands are complex
number objects.

Addition and subtraction of complex numbers


112
Python Tutorial

Addition and subtraction of complex numbers is a simple addition/subtraction of respective


real and imaginary components.

a=2.5+3.4j
b=-3+1.0j
print ("Addition of complex numbers - a=",a, "b=",b, "a+b=", a+b)
print ("Subtraction of complex numbers - a=",a, "b=",b, "a-b=", a-b)

It will produce the following output −

Addition of complex numbers - a= (2.5+3.4j) b= (-3+1j) a+b= (-0.5+4.4j)


Subtraction of complex numbers - a= (2.5+3.4j) b= (-3+1j) a-b= (5.5+2.4j)

Multiplication of complex numbers


Multiplication of complex numbers is similar to multiplication of two binomials in algebra.
If "a+bj" and "x+yj" are two complex numbers, then their multiplication is given by this
formula −

(a+bj)*(x+yj) = ax+ayj+xbj+byj2 = (ax-by)+(ay+xb)j

For example,

a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j

The following program confirms the result −

a=6+4j
b=3+2j
print ("Multplication of complex numbers - a=",a, "b=",b, "a*b=", a*b)

To understand the how the division of two complex numbers takes place, we should use
the conjugate of a complex number. Python's complex object has a conjugate() method
that returns a complex number with the sign of imaginary part reversed.

>>> a=5+6j
>>> [Link]()
(5-6j)

Division of complex numbers


To divide two complex numbers, divide and multiply the numerator as well as the
denominator with the conjugate of denominator.

113
Python Tutorial

a=6+4j
b=3+2j
c=a/b
c=(6+4j)/(3+2j)
c=(6+4j)*(3-2j)/3+2j)*(3-2j)
c=(18-12j+12j+8)/(9-6j+6j+4)
c=26/13
c=2+0j

To verify, run the following code −

a=6+4j
b=3+2j
print ("Division of complex numbers - a=",a, "b=",b, "a/b=", a/b)

Complex class in Python doesn't support the modulus operator (%) and floor division
operator (//).

114
18. Python - Comparison Operators
Python Tutorial

Python Comparison Operators


Comparison operators in Python are very important in Python's conditional statements (if,
else and elif) and looping statements (while and for loops). The comparison operators also
called relational operators. Some of the well known operators are "<" stands for less than,
and ">" stands for greater than operator.
Python uses two more operators, combining "=" symbol with these two. The "<=" symbol
is for less than or equal to operator and the ">=" symbol is for greater than or equal to
operator.

Different Comparison Operators in Python


Python has two more comparison operators in the form of "==" and "!=". They are for is
equal to and is not equal to operators. Hence, there are six comparison operators in Python
and they are listed below in this table:

Operator Name Example


< Less than a<b
> Greater than a>b
<= Less than or equal to a<=b
>= Greater than or equal to a>=b
== Is equal to a==b
!= Is not equal to a!=b
Comparison operators are binary in nature, requiring two operands. An expression
involving a comparison operator is called a Boolean expression, and always returns either
True or False.
Example

a=5
b=7
print (a>b)
print (a<b)

It will produce the following output −

False
True

Both the operands may be Python literals, variables or expressions. Since Python supports
mixed arithmetic, you can have any number type operands.
Example
The following code demonstrates the use of Python's comparison operators with integer
numbers −

115
Python Tutorial

print ("Both operands are integer")


a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

Both operands are integer


a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True

Comparison of Float Number


In the following example, an integer operand and a float operand are compared.
Example

print ("comparison of int and float")


a=10
b=10.0
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of int and float


a= 10 b= 10.0 a>b is False
a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False

Comparison of Complex Numbers


Although complex object is a number data type in Python, its behavior is different from
others. Python doesn't support < and > operators, however it does support equality (==)
and inequality (!=) operators.
Example

116
Python Tutorial

print ("comparison of complex numbers")


a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of complex numbers


a= (10+1j) b= (10-1j) a==b is False
a= (10+1j) b= (10-1j) a!=b is True
You get a TypeError with less than or greater than operators.

Example

print ("comparison of complex numbers")


a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)

It will produce the following output −

comparison of complex numbers


Traceback (most recent call last):
File "C:\Users\mlath\examples\[Link]", line 5, in <module>
print ("a=",a, "b=",b,"a<b is",a<b)
^^^
TypeError: '<' not supported between instances of 'complex' and
'complex

Comparison of Booleans
Boolean objects in Python are really integers: True is 1 and False is 0. In fact, Python
treats any non-zero number as True. In Python, comparison of Boolean objects is possible.
"False < True" is True!
Example

print ("comparison of Booleans")


a=True
b=False
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)

117
Python Tutorial

print ("a=",a, "b=",b,"a==b is",a==b)


print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of Booleans
a= True b= False a<b is False
a= True b= False a>b is True
a= True b= False a==b is False
a= True b= False a!=b is True

Comparison of Sequence Types


In Python, comparison of only similar sequence objects can be performed. A string object
is comparable with another string only. A list cannot be compared with a tuple, even if
both have same items.
Example

print ("comparison of different sequence types")


a=(1,2,3)
b=[1,2,3]
print ("a=",a, "b=",b,"a<b is",a<b)

It will produce the following output −

comparison of different sequence types


Traceback (most recent call last):
File "C:\Users\mlath\examples\[Link]", line 5, in <module>
print ("a=",a, "b=",b,"a<b is",a<b)
^^^
TypeError: '<' not supported between instances of 'tuple' and 'list'

Sequence objects are compared by lexicographical ordering mechanism. The comparison


starts from item at 0th index. If they are equal, comparison moves to next index till the
items at certain index happen to be not equal, or one of the sequences is exhausted. If
one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller
(lesser) one.
Which of the operands is greater depends on the difference in values of items at the index
where they are unequal. For example, 'BAT'>'BAR' is True, as T comes after R in Unicode
order.
If all items of two sequences compare equal, the sequences are considered equal.
Example

print ("comparison of strings")


a='BAT'

118
Python Tutorial

b='BALL'
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of strings
a= BAT b= BALL a<b is False
a= BAT b= BALL a>b is True
a= BAT b= BALL a==b is False
a= BAT b= BALL a!=b is True

In the following example, two tuple objects are compared −


Example

print ("comparison of tuples")


a=(1,2,4)
b=(1,2,3)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

a= (1, 2, 4) b= (1, 2, 3) a<b is False


a= (1, 2, 4) b= (1, 2, 3) a>b is True
a= (1, 2, 4) b= (1, 2, 3) a==b is False
a= (1, 2, 4) b= (1, 2, 3) a!=b is True

Comparison of Dictionary Objects


The use of "<" and ">" operators for Python's dictionary is not defined. In case of these
operands, TypeError: '<' not supported between instances of 'dict' and 'dict' is reported.
Equality comparison checks if the length of both the dict items is same. Length of
dictionary is the number of key-value pairs in it.
Python dictionaries are simply compared by length. The dictionary with fewer elements is
considered less than a dictionary with more elements.
Example

print ("comparison of dictionary objects")


a={1:1,2:2}

119
Python Tutorial

b={2:2, 1:1, 3:3}


print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of dictionary objects


a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a==b is False
a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a!=b is True

120
19. Python - Assignment Operators
Python Tutorial

Python Assignment Operator


The = (equal to) symbol is defined as assignment operator in Python. The value of Python
expression on its right is assigned to a single variable on its left. The = symbol as in
programming in general (and Python in particular) should not be confused with its usage
in Mathematics, where it states that the expressions on the either side of the symbol are
equal.
Example of Assignment Operator in Python
Consider following Python statements −

a = 10
b = 5
a = a + b
print (a)

At the first instance, at least for somebody new to programming but who knows maths,
the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs
to be reemphasized that the = symbol is an assignment operator here and not used to
show the equality of LHS and RHS.
Because it is an assignment, the expression on right evaluates to 15, the value is assigned
to a.
In the statement "a+=b", the two operators "+" and "=" can be combined in a "+="
operator. It is called as add and assign operator. In a single statement, it performs addition
of two operands "a" and "b", and result is assigned to operand on left, i.e. "a".

Augmented Assignment Operators in Python


In addition to the simple assignment operators, Python provides few more assignment
operators for advanced use. They are called cumulative or augmented assignment
operators. In this chapter, we shall learn to use augmented assignment operators defined
in Python.
Python has the augmented assignment operators for all arithmetic and comparison
operators.
Python augmented assignment operators combines addition and assignment in one
statement. Since Python supports mixed arithmetic, the two operands may be of different
types. However, the type of left operand changes to the operand of on right, if it is wider.
Example
The += operator is an augmented operator. It is also called cumulative addition operator,
as it adds "b" in "a" and assigns the result back to a variable.
The following are the augmented assignment operators in Python:

121
Python Tutorial

 Augmented Addition Operator


 Augmented Subtraction Operator
 Augmented Multiplication Operator
 Augmented Division Operator
 Augmented Modulus Operator
 Augmented Exponent Operator
 Augmented Floor division Operator

Augmented Addition Operator (+=)


Following examples will help in understanding how the "+=" operator works −

a=10
b=5
print ("Augmented addition of int and int")
a+=b # equivalent to a=a+b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented addition of int and float")
a+=b # equivalent to a=a+b
print ("a=",a, "type(a):", type(a))

a=10.50
b=5+6j
print ("Augmented addition of float and complex")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented addition of int and int
a= 15 type(a): <class 'int'>
Augmented addition of int and float
a= 15.5 type(a): <class 'float'>
Augmented addition of float and complex
a= (15.5+6j) type(a): <class 'complex'>

Augmented Subtraction Operator (-=)


Use -= symbol to perform subtract and assign operations in a single statement. The "a-
=b" statement performs "a=a-b" assignment. Operands may be of any number type.
Python performs implicit type casting on the object which is narrower in size.

122
Python Tutorial

a=10
b=5
print ("Augmented subtraction of int and int")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented subtraction of int and float")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

a=10.50
b=5+6j
print ("Augmented subtraction of float and complex")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented subtraction of int and int


a= 5 type(a): <class 'int'>
Augmented subtraction of int and float
a= 4.5 type(a): <class 'float'>
Augmented subtraction of float and complex
a= (5.5-6j) type(a): <class 'complex'>

Augmented Multiplication Operator (*=)


The "*=" operator works on similar principle. "a*=b" performs multiply and assign
operations, and is equivalent to "a=a*b". In case of augmented multiplication of two
complex numbers, the rule of multiplication as discussed in the previous chapter is
applicable.

a=10
b=5
print ("Augmented multiplication of int and int")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

123
Python Tutorial

a=10
b=5.5
print ("Augmented multiplication of int and float")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

a=6+4j
b=3+2j
print ("Augmented multiplication of complex and complex")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented multiplication of int and int


a= 50 type(a): <class 'int'>
Augmented multiplication of int and float
a= 55.0 type(a): <class 'float'>
Augmented multiplication of complex and complex
a= (10+24j) type(a): <class 'complex'>

Augmented Division Operator (/=)


The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is
equivalent to "a=a/b". The division operation of int or float operands is float. Division of
two complex numbers returns a complex number. Given below are examples of augmented
division operator.

a=10
b=5
print ("Augmented division of int and int")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented division of int and float")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

124
Python Tutorial

a=6+4j
b=3+2j
print ("Augmented division of complex and complex")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented division of int and int


a= 2.0 type(a): <class 'float'>
Augmented division of int and float
a= 1.8181818181818181 type(a): <class 'float'>
Augmented division of complex and complex
a= (2+0j) type(a): <class 'complex'>

Augmented Modulus Operator (%=)


To perform modulus and assignment operation in a single statement, use the %= operator.
Like the mod operator, its augmented version also is not supported for complex number.

a=10
b=5
print ("Augmented modulus operator with int and int")
a%=b #equivalent to a=a%b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented modulus operator with int and float")
a%=b #equivalent to a=a%b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented modulus operator with int and int


a= 0 type(a): <class 'int'>
Augmented modulus operator with int and float
a= 4.5 type(a): <class 'float'>

Augmented Exponent Operator (**=)


The "**=" operator results in computation of "a" raised to "b", and assigning the value
back to "a". Given below are some examples −

125
Python Tutorial

a=10
b=5
print ("Augmented exponent operator with int and int")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented exponent operator with int and float")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

a=6+4j
b=3+2j
print ("Augmented exponent operator with complex and complex")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented exponent operator with int and int


a= 100000 type(a): <class 'int'>
Augmented exponent operator with int and float
a= 316227.7660168379 type(a): <class 'float'>
Augmented exponent operator with complex and complex
a= (97.52306038414744-62.22529992036203j) type(a): <class 'complex'>

Augmented Floor division Operator (//=)


For performing floor division and assignment in a single statement, use the "//=" operator.
"a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

a=10
b=5
print ("Augmented floor division operator with int and int")
a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5

126
Python Tutorial

print ("Augmented floor division operator with int and float")


a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented floor division operator with int and int


a= 2 type(a): <class 'int'>
Augmented floor division operator with int and float
a= 1.0 type(a): <class 'float'>

127
20. Python - Logical Operators Python Tutorial

Python Logical Operators


Python logical operators are used to form compound Boolean expressions. Each operand
for these logical operators is itself a Boolean expression. For example,
Example

age > 16 and marks > 80


percentage < 50 or attendance < 75

Along with the keyword False, Python interprets None, numeric zero of all types, and
empty sequences (strings, tuples, lists), empty dictionaries, and empty sets as False. All
other values are treated as True.
There are three logical operators in Python. They are "and", "or" and "not". They must be
in lowercase.

Logical "and" Operator


For the compound Boolean expression to be True, both the operands must be True. If any
or both operands evaluate to False, the expression returns False.

Logical "and" Operator Truth Table


The following table shows the scenarios.

a b a and b
F F F
F T F
T F F
T T T

Logical "or" Operator


In contrast, the or operator returns True if any of the operands is True. For the compound
Boolean expression to be False, both the operands have to be False.

Logical "or" Operator Truth Table


The following table shows the result of the "or" operator with different conditions:

a b a or b
F F F
F T T
T F T
T T T

128
Python Tutorial

Logical "not" Operator


This is a unary operator. The state of Boolean operand that follows, is reversed. As a
result, not True becomes False and not False becomes True.

Logical "not" Operator Truth Table


a not(a)
F T
T F

How the Python interpreter evaluates the logical operators?


The expression "x and y" first evaluates "x". If "x" is false, its value is returned; otherwise,
"y" is evaluated and the resulting value is returned.

The expression "x or y" first evaluates "x"; if "x" is true, its value is returned; otherwise,
"y" is evaluated and the resulting value is returned.

Python Logical Operators Examples


Some use cases of logical operators are given below −

129
Python Tutorial

Example 1: Logical Operators with Boolean Conditions


x = 10
y = 20
print("x > 0 and x < 10:",x > 0 and x < 10)
print("x > 0 and y > 10:",x > 0 and y > 10)
print("x > 10 or y > 10:",x > 10 or y > 10)
print("x%2 == 0 and y%2 == 0:",x%2 == 0 and y%2 == 0)
print ("not (x+y>15):", not (x+y)>15)

It will produce the following output −

x > 0 and x < 10: False


x > 0 and y > 10: True
x > 10 or y > 10: True
x%2 == 0 and y%2 == 0: True
not (x+y>15): False

Example 2: Logical Operators with Non- Boolean Conditions


We can use non-boolean operands with logical operators. Here, we need to not that any
non-zero numbers, and non-empty sequences evaluate to True. Hence, the same truth
tables of logical operators apply.
In the following example, numeric operands are used for logical operators. The variables
"x", "y" evaluate to True, "z" is False

x = 10
y = 20
z = 0
print("x and y:",x and y)
print("x or y:",x or y)
print("z or x:",z or x)
print("y or z:", y or z)

It will produce the following output −

x and y: 20
x or y: 10
z or x: 10
y or z: 20

Example 3: Logical Operators with Strings and Tuples

130
Python Tutorial

The string variable is treated as True and an empty tuple as False in the following example

a="Hello"
b=tuple()
print("a and b:",a and b)
print("b or a:",b or a)

It will produce the following output −

a and b: ()
b or a: Hello

Example 4: Logical Operators to Compare Sequences (Lists)


Finally, two list objects below are non-empty. Hence x and y returns the latter, and x or y
returns the former.

x=[1,2,3]
y=[10,20,30]
print("x and y:",x and y)
print("x or y:",x or y)

It will produce the following output −

x and y: [10, 20, 30]


x or y: [1, 2, 3]

131
21. Python - Bitwise Operators Python Tutorial

Python Bitwise Operators


Python bitwise operators are normally used to perform bitwise operations on integer-type
objects. However, instead of treating the object as a whole, it is treated as a string of bits.
Different operations are done on each bit in the string.
Python has six bitwise operators - &, |, ^, ~, << and >>. All these operators (except ~)
are binary in nature, in the sense they operate on two operands. Each operand is a binary
digit (bit) 1 or 0.
The following are the bitwise operators in Python -
 Bitwise AND Operator
 Bitwise OR Operator
 Bitwise XOR Operator
 Bitwise NOT Operator
 Bitwise Left Shift Operator
 Biwtise Right Shift Operator

Python Bitwise AND Operator (&)


Bitwise AND operator is somewhat similar to logical and operator. It returns True only if
both the bit operands are 1 (i.e. True). All the combinations are −

0 & 0 is 0
1 & 0 is 0
0 & 1 is 0
1 & 1 is 1

When you use integers as the operands, both are converted in equivalent binary, the &
operation is done on corresponding bit from each number, starting from the least
significant bit and going towards most significant bit.
Example of Bitwise AND Operator in Python
Let us take two integers 60 and 13, and assign them to variables a and b respectively.

a=60
b=13
print ("a:",a, "b:",b, "a&b:",a&b)

It will produce the following output −

a: 60 b: 13 a&b: 12

To understand how Python performs the operation, obtain the binary equivalent of each
variable.

print ("a:", bin(a))

132
Python Tutorial

print ("b:", bin(b))

It will produce the following output −

a: 0b111100
b: 0b1101

For the sake of convenience, use the standard 8-bit format for each number, so that "a"
is 00111100 and "b" is 00001101. Let us manually perform and operation on each
corresponding bits of these two numbers.

0011 1100
&
0000 1101
-------------
0000 1100

Convert the resultant binary back to integer. You'll get 12, which was the result obtained
earlier.

>>> int('00001100',2)
12

Python Bitwise OR Operator (|)


The "|" symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result
is 1 otherwise it is 0.

0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1

Example of Bitwise OR Operator in Python


Take the same values of a=60, b=13. The "|" operation results in 61. Obtain their binary
equivalents.

a=60
b=13
print ("a:",a, "b:",b, "a|b:",a|b)
print ("a:", bin(a))
print ("b:", bin(b))

It will produce the following output −

a: 60 b: 13 a|b: 61
a: 0b111100

133
Python Tutorial

b: 0b1101

To perform the "|" operation manually, use the 8-bit format.

0011 1100
|
0000 1101
-------------
0011 1101

Convert the binary number back to integer to tally the result −

>>> int('00111101',2)
61

Python Bitwise XOR Operator (^)


The term XOR stands for exclusive OR. It means that the result of OR operation on two
bits will be 1 if only one of the bits is 1.

0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0

Example of Bitwise XOR Operator in Python


Let us perform XOR operation on a=60 and b=13.

a=60
b=13
print ("a:",a, "b:",b, "a^b:",a^b)

It will produce the following output −

a: 60 b: 13 a^b: 49

We now perform the bitwise XOR manually.

0011 1100
^
0000 1101
-------------
0011 0001

The int() function shows 00110001 to be 49.

>>> int('00110001',2)
49

134
Python Tutorial

Python Bitwise NOT Operator (~)


This operator is the binary equivalent of logical NOT operator. It flips each bit so that 1 is
replaced by 0, and 0 by 1, and returns the complement of the original number. Python
uses 2's complement method. For positive integers, it is obtained simply by reversing the
bits. For negative number, -x, it is written using the bit pattern for (x-1) with all of the
bits complemented (switched from 1 to 0 or 0 to 1). Hence: (for 8 bit representation)

-1 is complement(1 - 1) = complement(0) = "11111111"


-10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110".

Example of Bitwise NOT Operator in Python


For a=60, its complement is −

a=60
print ("a:",a, "~a:", ~a)

It will produce the following output −

a: 60 ~a: -61

Python Bitwise Left Shift Operator (<<)


Left shift operator shifts most significant bits to right by the number on the right side of
the "<<" symbol. Hence, "x << 2" causes two bits of the binary representation of to right.
Example of Bitwise Left Shift Operator in Python
Let us perform left shift on 60.

a=60
print ("a:",a, "a<<2:", a<<2)

It will produce the following output −

a: 60 a<<2: 240

How does this take place? Let us use the binary equivalent of 60, and perform the left shift
by 2.

0011 1100
<<
2
-------------
1111 0000

Convert the binary to integer. It is 240.

>>> int('11110000',2)
240

Python Bitwise Right Shift Operator (>>)

135
Python Tutorial

Right shift operator shifts least significant bits to left by the number on the right side of
the ">>" symbol. Hence, "x >> 2" causes two bits of the binary representation of to left.
Example of Bitwise Right Shift Operator in Python
Let us perform right shift on 60.

a=60
print ("a:",a, "a>>2:", a>>2)

It will produce the following output −

a: 60 a>>2: 15

Manual right shift operation on 60 is shown below −

0011 1100
>>
2
-------------
0000 1111

Use int() function to covert the above binary number to integer. It is 15.

>>> int('00001111',2)
15

136
22. Python - Membership Operators
Python Tutorial

Python Membership Operators


The membership operators in Python help us determine whether an item is present in a
given container type object, or in other words, whether an item is a member of the given
container type object.

Types of Python Membership Operators


Python has two membership operators: in and not in. Both return a Boolean result. The
result of in operator is opposite to that of not in operator.

The 'in' Operator


The "in" operator is used to check whether a substring is present in a bigger string, any
item is present in a list or tuple, or a sub-list or sub-tuple is included in a list or tuple.
Example of Python Membership "in" Operator
In the following example, different substrings are checked whether they belong to the
string var="TutorialsPoint". Python differentiates characters on the basis of their Unicode
value. Hence "To" is not the same as "to". Also note that if the "in" operator returns True,
the "not in" operator evaluates to False.

var = "TutorialsPoint"
a = "P"
b = "tor"
c = "in"
d = "To"
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)
print (c, "in", var, ":", c in var)
print (d, "in", var, ":", d in var)

It will produce the following output −

P in TutorialsPoint : True
tor in TutorialsPoint : True
in in TutorialsPoint : True
To in TutorialsPoint : False

The 'not in' Operator


The "not in" operator is used to check a sequence with the given value is not present in
the object like string, list, tuple, etc.
137
Python Tutorial

Example of Python Membership "not in" Operator

var = "TutorialsPoint"
a = "P"
b = "tor"
c = "in"
d = "To"
print (a, "not in", var, ":", a not in var)
print (b, "not in", var, ":", b not in var)
print (c, "not in", var, ":", c not in var)
print (d, "not in", var, ":", d not in var)

It will produce the following output −

P not in TutorialsPoint : False


tor not in TutorialsPoint : False
in not in TutorialsPoint : False
To not in TutorialsPoint : True

Membership Operator with Lists and Tuples


You can use the "in/not in" operator to check the membership of an item in the list or
tuple.

var = [10,20,30,40]
a = 20
b = 10
c = a-b
d = a/2
print (a, "in", var, ":", a in var)
print (b, "not in", var, ":", b not in var)
print (c, "in", var, ":", c in var)
print (d, "not in", var, ":", d not in var)

It will produce the following output −

20 in [10, 20, 30, 40] : True


10 not in [10, 20, 30, 40] : False
10 in [10, 20, 30, 40] : True
10.0 not in [10, 20, 30, 40] : False

In the last case, "d" is a float but still it compares to True with 10 (an int) in the list. Even
if a number expressed in other formats like binary, octal or hexadecimal are given, the
membership operators tell if it is inside the sequence.
138
Python Tutorial

>>> 0x14 in [10, 20, 30, 40]


True

Example
However, if you try to check if two successive numbers are present in a list or tuple, the
in operator returns False. If the list/tuple contains the successive numbers as a sequence
itself, then it returns True.

var = (10,20,30,40)
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)
var = ((10,20),30,40)
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)

It will produce the following output −

(10, 20) in (10, 20, 30, 40) : False


(10, 20) in ((10, 20), 30, 40) : True

Membership Operator with Sets


Python's membership operators also work well with the set objects.

var = {10,20,30,40}
a = 10
b = 20
print (b, "in", var, ":", b in var)
var = {(10,20),30,40}
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)

It will produce the following output −

20 in {40, 10, 20, 30} : True


(10, 20) in {40, 30, (10, 20)} : True

Membership Operator with Dictionaries


Use of in as well as not in operators with dictionary object is allowed. However, Python
checks the membership only with the collection of keys and not values.

139
Python Tutorial

var = {1:10, 2:20, 3:30}


a = 2
b = 20
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)

It will produce the following output −

2 in {1: 10, 2: 20, 3: 30} : True


20 in {1: 10, 2: 20, 3: 30} : False

140
23. Python - Identity Operators Python Tutorial

Python Identity Operators


The identity operators compare the objects to determine whether they share the same
memory and refer to the same object type (data type).
Python provided two identity operators; we have listed them as follows:
 'is' Operator
 'is not' Operator

Python 'is' Operator


The 'is' operator evaluates to True if both the operand objects share the same memory
location. The memory location of the object can be obtained by the "id()" function. If the
"id()" of both variables is same, the "is" operator returns True.
Example of Python Identity 'is' Operator

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

# Comparing and printing return values


print(a is c)
print(a is b)

# Printing IDs of a, b, and c


print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))

It will produce the following output −

True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456

Python 'is not' Operator

141
Python Tutorial

The 'is not' operator evaluates to True if both the operand objects do not share the same
memory location or both operands are not the same objects.
Example of Python Identity 'is not' Operator

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

# Comparing and printing return values


print(a is not c)
print(a is not b)

# Printing IDs of a, b, and c


print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))

It will produce the following output −

False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176

Python Identity Operators Examples with Explanations


Example 1

a="TutorialsPoint"
b=a
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 2739311598832 2739311598832


a is b: True
b is not a: False

The list and tuple objects behave differently, which might look strange in the first instance.
In the following example, two lists "a" and "b" contain same items. But their id() differs.

142
Python Tutorial

Example 2

a=[1,2,3]
b=[1,2,3]
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 1552612704640 1552567805568


a is b: False
b is not a: True

The list or tuple contains the memory locations of individual items only and not the items
itself. Hence "a" contains the addresses of 10,20 and 30 integer objects in a certain
location which may be different from that of "b".
Example 3

print (id(a[0]), id(a[1]), id(a[2]))


print (id(b[0]), id(b[1]), id(b[2]))

It will produce the following output −

140734682034984 140734682035016 140734682035048


140734682034984 140734682035016 140734682035048

Because of two different locations of "a" and "b", the "is" operator returns False even if
the two lists contain same numbers.

143
24. Python Operator PrecedencePython Tutorial

Python Operator Precedence


An expression may have multiple operators to be evaluated. The operator precedence
defines the order in which operators are evaluated. In other words, the order of operator
evaluation is determined by the operator precedence.
If a certain expression contains multiple operators, their order of evaluation is determined
by the order of precedence. For example, consider the following expression

>>> a = 2+3*5

Here, what will be the value of a? - yes it will be 17 (multiply 3 by 5 first and then add 2)
or 25 (adding 2 and 3 and then multiply with 5)? Python’s operator precedence rule comes
into picture here.
If we consider only the arithmetic operators in Python, the traditional BODMAS rule is also
employed by Python interpreter, where the brackets are evaluated first, the division and
multiplication operators next, followed by addition and subtraction operators. Hence, a will
become 17 in the above expression.
In addition to the operator precedence, the associativity of operators is also important. If
an expression consists of operators with same level of precedence, the associativity
determines the order. Most of the operators have left to right associativity. It means, the
operator on the left is evaluated before the one on the right.
Let us consider another expression:

>>> b = 10/5*4

In this case, both * (multiplication) and / (division) operators have same level of
precedence. However, the left to right associativity rule performs the division first (10/5
= 2) and then the multiplication (2*4 = 8).

Python Operator Precedence Table


The following table lists all the operators in Python in their decreasing order of precedence.
Operators in the same cell under the Operators column have the same precedence.

[Link]. Operator & Description


(),[], {}
1
Parentheses and braces
[index], [index:index]
2
Subscription, slicing,
await x
3
Await expression
**
4
Exponentiation
+x, -x, ~x
5
Positive, negative, bitwise NOT

144
Python Tutorial

*, @, /, //, %

6 Multiplication, matrix
multiplication, division, floor
division, remainder
+, -
7
Addition and subtraction
<<, >>
8
Left Shifts, Right Shifts
&
9
Bitwise AND
^
10
Bitwise XOR
|
11
Bitwise OR
in, not in, is, is not, <, <=,
>, >=, !=, ==
12 Comparisons, including
membership tests and identity
tests
not x
13
Boolean NOT
and
14
Boolean AND
or
15
Boolean OR
if – else
16
Conditional expression
lambda
17
Lambda expression
:=
18
Walrus operator

Python Operator Precedence Example


a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)

145
Python Tutorial

e = (a + b) * (c / d); # (30) * (15/5)


print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

146
25. Python - Comments Python Tutorial

Python Comments
Python comments are programmer-readable explanation or annotations in the Python
source code. They are added with the purpose of making the source code easier for
humans to understand, and are ignored by Python interpreter. Comments enhance the
readability of the code and help the programmers to understand the code very carefully.
Example
If we execute the code given below, the output produced will simply print "Hello, World!"
to the console, as comments are ignored by the Python interpreter and do not affect the
execution of the program −

# This is a comment
print("Hello, World!")

Python supports three types of comments as shown below −


 Single-line comments
 Multi-line comments
 Docstring Comments

Single Line Comments in Python


Single-line comments in Python start with a hash symbol (#) and extend to the end of the
line. They are used to provide short explanations or notes about the code. They can be
placed on their own line above the code they describe, or at the end of a line of code
(known as an inline comment) to provide context or clarification about that specific line.
Example: Standalone Single-Line Comment
A standalone single-line comment is a comment that occupies an entire line by itself,
starting with a hash symbol (#). It is placed above the code it describes or annotates.
In this example, the standalone single-line comment is placed above the "greet" function
"−

# Standalone single line comment is placed here


def greet():
print("Hello, World!")
greet()

Example: Inline Single-Line Comment


An inline single-line comment is a comment that appears on the same line as a piece of
code, following the code and preceded by a hash symbol (#).
Here the inline single-line comment follows the print("Hello, World!") statement −

print("Hello, World!") # Inline single line comment is placed here

147
Python Tutorial

Multi Line Comments in Python


In Python, multi-line comments are used to provide longer explanations or notes that span
multiple lines. While Python does not have a specific syntax for multi-line comments, there
are two common ways to achieve this: consecutive single-line comments and triple-quoted
strings −
Consecutive Single-Line Comments
Consecutive single-line comments refer to using the hash symbol (#) at the beginning of
each line. This method is often used for longer explanations or to sections of parts of the
code.
Example
In this example, multiple lines of comments are used to explain the purpose and logic of
the factorial function −

# This function calculates the factorial of a number


# using an iterative approach. The factorial of a number
# n is the product of all positive integers less than or
# equal to n. For example, factorial(5) is 5*4*3*2*1 = 120.
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result

number = 5
print(f"The factorial of {number} is {factorial(number)}")

Multi Line Comment Using Triple Quoted Strings


We can use triple-quoted strings (''' or """) to create multi-line comments. These strings
are technically string literals but can be used as comments if they are not assigned to any
variable or used in expressions.
This pattern is often used for block comments or when documenting sections of code that
require detailed explanations.
Example
Here, the triple-quoted string provides a detailed explanation of the "gcd" function,
describing its purpose and the algorithm used −

"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm. The GCD of

148
Python Tutorial

two numbers is the largest number that divides both of them


without leaving a remainder.
"""
def gcd(a, b):
while b:
a, b = b, a % b
return a

result = gcd(48, 18)


print("The GCD of 48 and 18 is:", result)

Using Comments for Documentation


In Python, documentation comments, also known as docstrings, provide a way to
incorporate documentation within your code. This can be useful for explaining the purpose
and usage of modules, classes, functions, and methods. Effective use of documentation
comments helps other developers understand your code and its purpose without needing
to read through all the details of the implementation.

Python Docstrings
In Python, docstrings are a special type of comment that is used to document modules,
classes, functions, and methods. They are written using triple quotes (''' or """) and are
placed immediately after the definition of the entity they document.
Docstrings can be accessed programmatically, making them an integral part of Python’s
built-in documentation tools.
Example of a Function Docstring

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
print(f"Hello, {name}!")
greet("Alice")

149
Python Tutorial

Accessing Docstrings
Docstrings can be accessed using the .__doc__ attribute or the help() function. This makes
it easy to view the documentation for any module, class, function, or method directly from
the interactive Python shell or within the code.
Example: Using the .__doc__ attribute

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
print(greet.__doc__)

Example: Using the help() Function

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
help(greet)

150
26. Python - User Input Python Tutorial

Provide User Input in Python


In this chapter, we will learn how Python accepts the user input from the console, and
displays the output on the same console.
Every computer application should have a provision to accept input from the user when it
is running. This makes the application interactive. Depending on how it is developed, an
application may accept the user input in the form of text entered in the console
([Link]), a graphical layout, or a web-based interface.

Python User Input Functions


Python provides us with two built-in functions to read the input from the keyboard.
 The input () Function
 The raw_input () Function
Python interpreter works in interactive and scripted mode. While the interactive mode is
good for quick evaluations, it is less productive. For repeated execution of same set of
instructions, scripted mode should be used.
Let us write a simple Python script to start with.

#! /usr/bin/python3.11
name = "Kiran"
city = "Hyderabad"
print ("Hello My name is", name)
print ("I am from", city)

Save the above code as [Link] and run it from the command-line. Here's the output

C:\python311> python [Link]


Hello My name is Kiran
I am from Hyderabad

The program simply prints the values of the two variables in it. If you run the program
repeatedly, the same output will be displayed every time. To use the program for another
name and city, you can edit the code, change name to say "Ravi" and city to "Chennai".
Every time you need to assign different value, you will have to edit the program, save and
run, which is not the ideal way.

The input() Function


Obviously, you need some mechanism to assign different values to the variable in the
runtime − while the program is running. Python's input() function does the same job.
Following is the syntax of Python's standard library input() function.

151
Python Tutorial

>>> var = input()

When the interpreter encounters input() function, it waits for the user to enter data from
the standard input stream (keyboard) till the Enter key is pressed. The sequence of
characters may be stored in a string variable for further use.
On reading the Enter key, the program proceeds to the next statement. Let change our
program to store the user input in name and city variables.

#! /usr/bin/python3.11
name = input()
city = input()

print ("Hello My name is", name)


print ("I am from ", city)

When you run, you will find the cursor waiting for user's input. Enter values for name and
city. Using the entered data, the output will be displayed.

Ravi
Chennai
Hello My name is Ravi
I am from Chennai

Now, the variables are not assigned any specific value in the program. Every time you run,
different values can be input. So, your program has become truly interactive.
Inside the input() function, you may give a prompt text, which will appear before the
cursor when you run the code.

#! /usr/bin/python3.11
name = input("Enter your name : ")
city = input("Enter your city : ")
print ("Hello My name is", name)
print ("I am from ", city)

When you run the program displays the prompt message, basically helping the user what
to enter.

Enter your name: Praveen Rao


Enter your city: Bengaluru
Hello My name is Praveen Rao
I am from Bengaluru

The raw_input() Function


The raw_input() function works similar to input() function. Here only point is that this
function was available in Python 2.7, and it has been renamed to input() in Python 3.6

152
Python Tutorial

Following is the syntax of the raw_input() function:

>>> var = raw_input ([prompt text])

Let's re-write the above program using raw_input() function:

#! /usr/bin/python3.11

name = raw_input("Eneter your name - ")


city = raw_input("Enter city name - ")

print ("Hello My name is", name)


print ("I am from ", city)

When you run, you will find the cursor waiting for user's input. Enter values for name and
city. Using the entered data, the output will be displayed.

Eneter your name - Ravi


Enter city name - Chennai
Hello My name is Ravi
I am from Chennai

Taking Numeric Input in Python


Let us write a Python code that accepts width and height of a rectangle from the user and
computes the area.

#! /usr/bin/python3.11

width = input("Enter width : ")


height = input("Enter height : ")

area = width*height
print ("Area of rectangle = ", area)

Run the program, and enter width and height.

Enter width: 20
Enter height: 30
Traceback (most recent call last):
File "C:\Python311\[Link]", line 5, in <module>
area = width*height
TypeError: can't multiply sequence by non-int of type 'str'

153
Python Tutorial

Why do you get a TypeError here? The reason is, Python always read the user input as a
string. Hence, width="20" and height="30" are the strings and obviously you cannot
perform multiplication of two strings.
To overcome this problem, we shall use int(), another built-in function from Python's
standard library. It converts a string object to an integer.
To accept an integer input from the user, read the input in a string, and type cast it to
integer with int() function −

w = input("Enter width : ")


width = int(w)

h = input("Enter height : ")


height = int(h)

You can combine the input and type cast statements in one −

#! /usr/bin/python3.11

width = int(input("Enter width : "))


height = int(input("Enter height : "))

area = width*height
print ("Area of rectangle = ", area)

Now you can input any integer value to the two variables in the program −

Enter width: 20
Enter height: 30
Area of rectangle = 600

Python's float() function converts a string into a float object. The following program
accepts the user input and parses it to a float variable − rate, and computes the interest
on an amount which is also input by the user.

#! /usr/bin/python3.11

amount = float(input("Enter Amount : "))


rate = float(input("Enter rate of interest : "))

interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)

The program ask user to enter amount and rate; and displays the result as follows −

Enter Amount: 12500

154
Python Tutorial

Enter rate of interest: 6.5


Amount: 12500.0 Interest: 812.5

The print() Function


Python's print() function is a built-in function. It is the most frequently used function, that
displays value of Python expression given in parenthesis, on Python's console, or standard
output ([Link]).

print ("Hello World ")

Any number of Python expressions can be there inside the parenthesis. They must be
separated by comma symbol. Each item in the list may be any Python object, or a valid
Python expression.

#! /usr/bin/python3.11

a = "Hello World"
b = 100
c = 25.50
d = 5+6j
print ("Message: a)
print (b, c, b-c)
print(pow(100, 0.5), pow(c,2))

The first call to print() displays a string literal and a string variable. The second prints
value of two variables and their subtraction. The pow() function computes the square root
of a number and square value of a variable.

Message Hello World


100 25.5 74.5
10.0 650.25

If there are multiple comma separated objects in the print() function's parenthesis, the
values are separated by a white space " ". To use any other character as a separator,
define a sep parameter for the print() function. This parameter should follow the list of
expressions to be printed.
In the following output of print() function, the variables are separated by comma.

#! /usr/bin/python3.11

city="Hyderabad"
state="Telangana"
country="India"
print(city, state, country, sep=',')

155
Python Tutorial

The effect of sep=',' can be seen in the result −

Hyderabad,Telangana,India

The print() function issues a newline character ('\n') at the end, by default. As a result,
the output of the next print() statement appears in the next line of the console.

city="Hyderabad"
state="Telangana"
print("City:", city)
print("State:", state)

Two lines are displayed as the output −

City: Hyderabad
State: Telangana

To make these two lines appear in the same line, define end parameter in the first print()
function and set it to a whitespace string " ".

city="Hyderabad"
state="Telangana"
country="India"

print("City:", city, end=" ")


print("State:", state)

Output of both the print() functions appear in continuation.

City: Hyderabad State: Telangana

156
27. Python - Numbers Python Tutorial

Python has built-in support to store and process numeric data (Python Numbers). Most
of the times you work with numbers in almost every Python application. Obviously, any
computer application deals with numbers. This tutorial will discuss about different types
of Python Numbers and their properties.

Python - Number Types


There are three built-in number types available in Python:
 integers (int)
 floating point numbers (float)
 complex numbers
Python also has a bult-in Boolean data type called bool. It can be treated as a sub-type of
int type, since it's two possible values True and False represent the integers 1 and 0
respectively.

Python − Integer Numbers


In Python, any number without the provision to store a fractional part is an integer. (Note
that if the fractional part in a number is 0, it doesn't mean that it is an integer. For
example, a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric
value is 10.) An integer can be zero, positive or a negative whole number. For example,
1234, 0, -55 all represent to integers in Python.
There are three ways to form an integer object. With (a) literal representation, (b) any
expression evaluating to an integer, and (c) using int() function.
Literal is a notation used to represent a constant directly in the source code. For example

>>> a =10

However, look at the following assignment of the integer variable c.

a = 10
b = 20
c = a + b

print ("a:", a, "type:", type(a))


print ("c:", c, "type:", type(c))

It will produce the following output −

a: 10 type: <class 'int'>


c: 30 type: <class 'int'>

157
Python Tutorial

Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its
value is indirectly assigned to c.
The third method of forming an integer object is with the return value of int() function. It
converts a floating point number or a string to an integer.

>>> a=int(10.5)
>>> b=int("100")

You can represent an integer as a binary, octal or hexa-decimal number. However,


internally the object is stored as an integer.

Binary Numbers in Python


A number consisting of only the binary digits (1 and 0) and prefixed with "0b" is a binary
number. If you assign a binary number to a variable, it still is an int variable.
A represent an integer in binary form, store it directly as a literal, or use int() function, in
which the base is set to 2

a=0b101
print ("a:",a, "type:",type(a))

b=int("0b101011", 2)
print ("b:",b, "type:",type(b))

It will produce the following output −

a: 5 type: <class 'int'>


b: 43 type: <class 'int'>

There is also a bin() function in Python. It returns a binary string equivalent of an integer.

a=43
b=bin(a)
print ("Integer:",a, "Binary equivalent:",b)

It will produce the following output −

Integer: 43 Binary equivalent: 0b101011

Octal Numbers in Python


An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses
octal notation, it needs to be prefixed by "0o" (lowercase O) or "0O" (uppercase O). A
literal representation of octal number is as follows −

a=0O107
print (a, type(a))

It will produce the following output −

71 <class 'int'>

158
Python Tutorial

Note that the object is internally stored as integer. Decimal equivalent of octal number
107 is 71.
Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int()
function to convert an octal string to integer, you need to set the base argument to 8.

a=int('20',8)
print (a, type(a))

It will produce the following output −

16 <class 'int'>

Decimal equivalent of octal 30 is 16.


In the following code, two int objects are obtained from octal notations and their addition
is performed.

a=0O56
print ("a:",a, "type:",type(a))

b=int("0O31",8)
print ("b:",b, "type:",type(b))

c=a+b
print ("addition:", c)

It will produce the following output −

a: 46 type: <class 'int'>


b: 25 type: <class 'int'>
addition: 71

To obtain the octal string for an integer, use oct() function.

a=oct(71)
print (a, type(a))

Hexa-decimal Numbers in Python


As the name suggests, there are 16 symbols in the Hexadecimal number system. They
are 0-9 and A to F. The first 10 digits are same as decimal digits. The alphabets A, B, C,
D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases
may be used for these letter symbols.
For the literal representation of an integer in Hexadecimal notation, prefix it by "0x" or
"0X".

a=0XA2
print (a, type(a))

159
Python Tutorial

It will produce the following output −

162 <class 'int'>

To convert a hexadecimal string to integer, set the base to 16 in the int() function.

a=int('0X1e', 16)
print (a, type(a))

Try out the following code snippet. It takes a Hexadecimal string, and returns the integer.

num_string = "A1"
number = int(num_string, 16)
print ("Hexadecimal:", num_string, "Integer:",number)

It will produce the following output −

Hexadecimal: A1 Integer: 161

However, if the string contains any symbol apart from the Hexadecimal symbol chart an
error will be generated.

num_string = "A1X001"
print (int(num_string, 16))

The above program generates the following error −

Traceback (most recent call last):


File "/home/[Link]", line 2, in
print (int(num_string, 16))
ValueError: invalid literal for int() with base 16: 'A1X001'

Python's standard library has hex() function, with which you can obtain a hexadecimal
equivalent of an integer.

a=hex(161)
print (a, type(a))

It will produce the following output −

0xa1 <class 'str'>

Though an integer can be represented as binary or octal or hexadecimal, internally it is


still integer. So, when performing arithmetic operation, the representation doesn't matter.

a=10 #decimal
b=0b10 #binary
c=0O10 #octal
d=0XA #Hexadecimal
e=a+b+c+d

160
Python Tutorial

print ("addition:", e)

It will produce the following output −

addition: 30

Python − Floating Point Numbers


A floating point number has an integer part and a fractional part, separated by a decimal
point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative
number.
A floating point number is an object of Python's float class. To store a float object, you
may use a literal notation, use the value of an arithmetic expression, or use the return
value of float() function.
Using literal is the most direct way. Just assign a number with fractional part to a variable.
Each of the following statements declares a float object.

>>> a=9.99
>>> b=0.999
>>> c=-9.99
>>> d=-0.999

In Python, there is no restriction on how many digits after the decimal point can a floating
point number have. However, to shorten the representation, the E or e symbol is used. E
stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10
raised to -3.
In scientific notation, number has a coefficient and exponent part. The coefficient should
be a float greater than or equal to 1 but less than 10. Hence, 1.23E+3, 9.9E-5, and 1E10
are the examples of floats with scientific notation.

>>> a=1E10
>>> a
10000000000.0
>>> b=9.90E-5
>>> b
9.9e-05
>>> 1.23E3
1230.0

The second approach of forming a float object is indirect, using the result of an expression.
Here, the quotient of two floats is assigned to a variable, which refers to a float object.

a=10.33
b=2.66
c=a/b

161
Python Tutorial

print ("c:", c, "type", type(c))

It will produce the following output −

c: 3.8834586466165413 type <class 'float'>

Python's float() function returns a float object, parsing a number or a string if it has the
appropriate contents. If no arguments are given in the parenthesis, it returns 0.0, and for
an int argument, fractional part with 0 is added.

>>> a=float()
>>> a
0.0
>>> a=float(10)
>>> a
10.0

Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns
a float with fractional part as 0.

a=float(0b10)
b=float(0O10)
c=float(0xA)

print (a,b,c, sep=",")

It will produce the following output −

2.0,8.0,10.0

The float() function retrieves a floating point number out of a string that encloses a float,
either in standard decimal point format, or having scientific notation.

a=float("-123.54")
b=float("1.23E04")
print ("a=",a,"b=",b)

It will produce the following output −

a= -123.54 b= 12300.0

In mathematics, infinity is an abstract concept. Physically, infinitely large number can


never be stored in any amount of memory. For most of the computer hardware
configurations, however, a very large number with 400th power of 10 is represented by
Inf. If you use "Infinity" as argument for float() function, it returns Inf.

a=1.00E400
print (a, type(a))
a=float("Infinity")

162
Python Tutorial

print (a, type(a))

It will produce the following output −

inf <class 'float'>


inf <class 'float'>

One more such entity is Nan (stands for Not a Number). It represents any value that is
undefined or not representable.

>>> a=float('Nan')
>>> a
Nan

Python − Complex Numbers


In this section, we shall know in detail about Complex data type in Python. Complex
numbers find their applications in mathematical equations and laws in electromagnetism,
electronics, optics, and quantum theory. Fourier transforms use complex numbers. They
are used in calculations with wavefunctions, designing filters, signal integrity in digital
electronics, radio astronomy, etc.
A complex number consists of a real part and an imaginary part, separated by either "+"
or "−". The real part can be any floating point (or itself a complex number) number. The
imaginary part is also a float/complex, but multiplied by an imaginary number.

In mathematics, an imaginary number "i" is defined as the square root of -1 (√-1).


Therefore, a complex number is represented as "x+yi", where x is the real part, and "y"
is the coefficient of imaginary part.
Quite often, the symbol "j" is used instead of "I" for the imaginary number, to avoid
confusion with its usage as current in theory of electricity. Python also uses "j" as the
imaginary number. Hence, "x+yj" is the representation of complex number in Python.
Like int or float data type, a complex object can be formed with literal representation or
using complex() function. All the following statements form a complex object.

>>> a=5+6j
>>> a
(5+6j)
>>> type(a)
<class 'complex'>
>>> a=2.25-1.2J
>>> a
(2.25-1.2j)
>>> type(a)
<class 'complex'>
>>> a=1.01E-2+2.2e3j

163
Python Tutorial

>>> a
(0.0101+2200j)
>>> type(a)
<class 'complex'>

Note that the real part as well as the coefficient of imaginary part have to be floats, and
they may be expressed in standard decimal point notation or scientific notation.
Python's complex() function helps in forming an object of complex type. The function
receives arguments for real and imaginary part, and returns the complex number.
There are two versions of complex() function, with two arguments and with one argument.
Use of complex() with two arguments is straightforward. It uses first argument as real
part and second as coefficient of imaginary part.

a=complex(5.3,6)
b=complex(1.01E-2, 2.2E3)
print ("a:", a, "type:", type(a))
print ("b:", b, "type:", type(b))

It will produce the following output −

a: (5.3+6j) type: <class 'complex'>


b: (0.0101+2200j) type: <class 'complex'>

In the above example, we have used x and y as float parameters. They can even be of
complex data type.

a=complex(1+2j, 2-3j)
print (a, type(a))

It will produce the following output −

(4+4j) <class 'complex'>

Surprised by the above example? Put "x" as 1+2j and "y" as 2-3j. Try to perform manual
computation of "x+yj" and you'll come to know.

complex(1+2j, 2-3j)
=(1+2j)+(2-3j)*j
=1+2j +2j+3
=4+4j

If you use only one numeric argument for complex() function, it treats it as the value of
real part; and imaginary part is set to 0.

a=complex(5.3)
print ("a:", a, "type:", type(a))

It will produce the following output −

164
Python Tutorial

a: (5.3+0j) type: <class 'complex'>

The complex() function can also parse a string into a complex number if its only argument
is a string having complex number representation.
In the following snippet, user is asked to input a complex number. It is used as argument.
Since Python reads the input as a string, the function extracts the complex object from it.

a= "5.5+2.3j"
b=complex(a)
print ("Complex number:", b)

It will produce the following output −

Complex number: (5.5+2.3j)

Python's built-in complex class has two attributes real and imag − they return the real and
coefficient of imaginary part from the object.

a=5+6j
print ("Real part:", [Link], "Coefficient of Imaginary part:", [Link])

It will produce the following output −

Real part: 5.0 Coefficient of Imaginary part: 6.0

The complex class also defines a conjugate() method. It returns another complex number
with the sign of imaginary component reversed. For example, conjugate of x+yj is x-yj.

>>> a=5-2.2j
>>> [Link]()
(5+2.2j)

Number Type Conversion


Python converts numbers internally in an expression containing mixed types to a common
type for evaluation. But sometimes, you need to coerce a number explicitly from one type
to another to satisfy the requirements of an operator or function parameter.
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and imaginary
part zero. In the same way type complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x and y are numeric expressions
Let us see various numeric and math-related functions.

Theoretic and Representation Functions


Python includes following theoretic and representation functions in the math module −

[Link]. Function & Description


1 [Link](x)

165
Python Tutorial

The ceiling of x: the smallest integer not less than x

[Link](n,k)

2 This function is used to find the returns the number of ways to


choose "x" items from "y" items without repetition and without
order.

[Link](x, y)

3 This function returns a float with the magnitude (absolute value) of


x but the sign of y.

[Link](x, y)

4 This function is used to compare the values of to objects. This


function is deprecated in Python3.

[Link](x)
5 This function is used to calculate the absolute value of a given
integer.
[Link](n)
6
This function is used to find the factorial of a given integer.

[Link](x)
7
This function calculates the floor value of a given integer.

[Link](x, y)

8 The fmod() function in math module returns same result as


the "%" operator. However fmod() gives more accurate result of
modulo division than modulo operator.

[Link](x)

9 This function is used to calculate the mantissa and exponent of a


given number.

[Link](iterable)

10 This function returns the floating point sum of all numeric items in
an iterable i.e. list, tuple, array.

[Link](*integers)

11 This function is used to calculate the greatest common divisor of all


the given integers.

[Link]()

12 This function is used to determine whether two given numeric


values are close to each other.

13 [Link](x)

166
Python Tutorial

This function is used to determine whether the given number is a


finite number.

[Link](x)

14 This function is used to determine whether the given value is


infinity (+ve or, -ve).

[Link](x)
15 This function is used to determine whether the given number is
"NaN".
[Link](n)

16 This function calculates the integer square-root of the given non


negative integer.

[Link](*integers)

17 This function is used to calculate the least common factor of the


given integer arguments.

[Link](x, i)

18 This function returns product of first number with exponent of


second number. So, ldexp(x,y) returns x*2**y. This is inverse of
frexp() function.

[Link](x)
19 This returns the fractional and integer parts of x in a two-item
tuple.
[Link](x, y, steps)
20
This function returns the next floating-point value after x towards y.

[Link](n, k)

21 This function is used to calculate the permutation. It returns the


number of ways to choose x items from y items without repetition
and with order.

[Link](iterable, *, start)

22 This function is used to calculate the product of all numeric items in


the iterable (list, tuple) given as argument.

[Link](x,y)

23 This function returns the remainder of x with respect to y. This is


the difference x − n*y, where n is the integer closest to the
quotient x / y.

24 [Link](x)

167
Python Tutorial

This function returns integral part of the number, removing the


fractional part. trunc() is equivalent to floor() for positive x, and
equivalent to ceil() for negative x.

[Link](x)

25 This function returns the value of the least significant bit of the float
x. trunc() is equivalent to floor() for positive x, and equivalent to
ceil() for negative x.

Power and Logarithmic Functions


[Link]. Function & Description
[Link](x)

1 This function is used to calculate the cube root of a


number.

[Link](x)
2
This function calculate the exponential of x: ex

math.exp2(x)

3 This function returns 2 raised to power x. It is


equivalent to 2**x.

math.expm1(x)

4 This function returns e raised to the power x,


minus 1. Here e is the base of natural logarithms.

[Link](x)

5 This function calculates the natural logarithm of x,


for x> 0.

math.log1p(x)

6 This function returns the natural logarithm of 1+x


(base e). The result is calculated in a way which is
accurate for x near zero.

math.log2(x)

7 This function returns the base-2 logarithm of x.


This is usually more accurate than log(x, 2).

8 math.log10(x)

168
Python Tutorial

The base-10 logarithm of x for x> 0.

[Link](x, y)
9
The value of x**y.
[Link](x)
10
The square root of x for x > 0

Trigonometric Functions
Python includes following functions that perform trigonometric calculations in the math
module −

[Link]. Function & Description


[Link](x)
1
This function returns the arc cosine of x, in radians.

[Link](x)
2
This function returns the arc sine of x, in radians.

[Link](x)
3
This function returns the arc tangent of x, in radians.

math.atan2(y, x)
4
This function returns atan(y / x), in radians.

[Link](x)
5
This function returns the cosine of x radians.

[Link](x)
6
This function returns the sine of x radians.

[Link](x)
7
This function returns the tangent of x radians.

[Link](x, y)

8
This function returns the Euclidean norm, sqrt(x*x + y*y).

Angular conversion Functions


Following are the angular conversion function provided by Python math module −

[Link]. Function & Description


[Link](x)

1 This function converts the given angle from radians to


degrees.

2 [Link](x)

169
Python Tutorial

This function converts the given angle from degrees to


radians.

Mathematical Constants
The Python math module defines the following mathematical constants −

[Link]. Constants & Description


[Link]

1 This represents the mathematical constant pi, which


equals to "3.141592..." to available precision.

good.e

2 This represents the mathematical constant e, which is


equal to "2.718281..." to available precision.

math. number

3 This represents the mathematical constant Tau (denoted


by τ ). It is equivalent to the ratio of circumference to
radius, and is equal to 2Π.

[Link]

4 This represents positive infinity. For negative infinity


use "−[Link]".

math. in

5 This constant is a floating-point "not a number" (NaN)


value. Its value is equivalent to the output of
float('nan').

Hyperbolic Functions
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas
instead of circles. Following are the hyperbolic functions of the Python math module −

[Link]. Function & Description


[Link](x)

1 This function is used to calculate the inverse hyperbolic cosine


of the given value.

2 [Link](x)

170
Python Tutorial

This function is used to calculate the inverse hyperbolic sine of


a given number.

[Link](x)

3 This function is used to calculate the inverse hyperbolic


tangent of a number.

[Link](x)

4 This function is used to calculate the hyperbolic cosine of the


given value.

[Link](x)

5 This function is used to calculate the hyperbolic sine of a given


number.

[Link](x)

6 This function is used to calculate the hyperbolic tangent of a


number.

Special Functions
Following are the special functions provided by the Python math module −

[Link]. Function & Description


[Link](x)

1 This function returns the value of the Gauss error


function for the given parameter.

[Link](x)

2 This function is the complementary for the error


function. Value of erf(x) is equivalent to 1-erf(x).

[Link](x)

3 This is used to calculate the factorial of the complex


numbers. It is defined for all the complex numbers
except the non-positive integers.

[Link](x)

4 This function is used to calculate the natural logarithm of


the absolute value of the Gamma function at x.

171
Python Tutorial

Random Number Functions


Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes following functions in the random module.

[Link]. Function & Description


[Link](seq)
1
A random item from a list, tuple, or string.

[Link]([start,] stop [,step])


2
A randomly selected element from range(start, stop,
step)
[Link]()

3 A random float r, such that 0 is less than or equal to r


and r is less than 1

[Link]([x])

This function sets the integer starting value used in


4 generating random numbers. Call this function before
calling any other random module function. Returns
None.

[Link](seq)

5 This function is used to randomize the items of the given


sequence.

[Link](a, b)

6 This function returns a random floating point value r,


such that a is less than or equal to r and r is less than b.

Built-in Mathematical Functions


Following mathematical functions are built into the Python interpreter, hence you don't
need to import them from any module.

[Link]. Function & Description


Python abs() function

1 The abs() function returns the absolute value of x, i.e. the


positive distance between x and zero.

2 Python max() function

172
Python Tutorial

The max() function returns the largest of its arguments or


largest number from the iterable (list or tuple).

Python min() function

3 The function min() returns the smallest of its arguments


i.e. the value closest to negative infinity, or smallest
number from the iterable (list or tuple)

Python pow() function

4 The pow() function returns x raised to y. It is equivalent


to x**y.

Python round() Function

5 round() is a built-in function in Python. It returns x


rounded to n digits from the decimal point.

Python sum() function

The sum() function returns the sum of all numeric items


6 in any iterable (list or tuple). It has an
optional start argument which is 0 by default. If given,
the numbers in the list are added to start value.

173
28. Python - Booleans Python Tutorial

Python Booleans (bool)


In Python, bool is a sub-type of int type. A bool object has two possible values, and it is
initialized with Python keywords, True and False.
Example

>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)

A bool object is accepted as argument to type conversion functions. With True as


argument, the int() function returns 1, float() returns 1.0; whereas for False, they return
0 and 0.0 respectively. We have a one argument version of complex() function.
If the argument is a complex object, it is taken as real part, setting the imaginary
coefficient to 0.
Example

a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)

On running this code, you will get the following output −

bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)

Python Boolean Expression


Python boolean expression is an expression that evaluates to a Boolean value. It almost
always involves a comparison operator. In the below example, we will see how the
comparison operators can give us the Boolean values. The bool() method is used to return
the truth value of an expresison.

Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.

174
Python Tutorial

Below we have examples which use numbers streams and Boolean values as parameters
to the bool function. The results come out as true or false depending on the parameter.
Example

# Check true
a = True
print(bool(a))
# Check false
a = False
print(bool(a))
# Check 0
a = 0.0
print(bool(a))
# Check 1
a = 1.0
print(bool(a))
# Check Equality
a = 5
b = 10
print(bool( a==b))
# Check None
a = None
print(bool(a))
# Check an empty sequence
a = ()
print(bool(a))
# Check an emtpty mapping
a = {}
print(bool(a))
# Check a non empty string
a = 'Tutorialspoint'
print(bool(a))

175
Python Tutorial

Python Control Statements

176
29. Python - Control Flow Python Tutorial

Python program control flow is regulated by various types of conditional statements,


loops, and function calls. By default, the instructions in a computer program are
executed in a sequential manner, from top to bottom, or from start to end. However,
such sequentially executing programs can perform only simplistic tasks. We would like
the program to have a decision-making ability, so that it performs different steps
depending on different conditions.

Most programming languages including Python provide functionality to control the flow of
execution of instructions. Normally, there are two type of control flow statements in any
programming language and Python also supports them.

Decision Making Statements


Decision making statements are used in the Python programs to make them able to
decide which of the alternative group of instructions to be executed, depending on value
of a certain Boolean expression.

The following diagram illustrates how decision-making statements work −

The if Statements
Python provides if..elif..else control statements as a part of decision marking. It consists
of three different blocks, which are if block, elif (short of else if) block and else block.

177
Python Tutorial

Example
Following is a simple example which makes use of if..elif..else. You can try to run this
program using different marks and verify the result.

marks = 80
result = ""
if marks < 30:
result = "Failed"
elif marks > 75:
result = "Passed with distinction"
else:
result = "Passed"

print(result)

This will produce following result:

Passed with distinction

The match Statement


Python supports Match-Case statement, which can also be used as a part of decision
making. If a pattern matches the expression, the code under that case will execute.

Example
Following is a simple example which makes use of match statement.

def checkVowel(n):
match n:
case 'a': return "Vowel alphabet"
case 'e': return "Vowel alphabet"
case 'i': return "Vowel alphabet"
case 'o': return "Vowel alphabet"
case 'u': return "Vowel alphabet"
case _: return "Simple alphabet"
print (checkVowel('a'))
print (checkVowel('m'))
print (checkVowel('o'))

This will produce following result:

Vowel alphabet

178
Python Tutorial

Simple alphabet
Vowel alphabet

Loops or Iteration Statements


Most of the processes require a group of instructions to be repeatedly executed. In
programming terminology, it is called a loop. Instead of the next step, if the flow is
redirected towards any earlier step, it constitutes a loop.

The following diagram illustrates how the looping works −

If the control goes back unconditionally, it forms an infinite loop which is not desired as
the rest of the code would never get executed.

In a conditional loop, the repeated iteration of block of statements goes on till a certain
condition is met. Python supports a number of loops like for loop, while loop which we
will study in next chapters.

The for Loop


The for loop iterates over the items of any sequence, such as a list, tuple or a string.

Example
Following is an example which makes use of For Loop to iterate through an array in
Python:

words = ["one", "two", "three"]


for x in words:

179
Python Tutorial

print(x)

This will produce following result:

one
two
three

The while Loop


The while loop repeatedly executes a target statement as long as a given boolean
expression is true.

Example
Following is an example which makes use of While Loop to print first 5 numbers in
Python:

i = 1
while i < 6:
print(i)
i += 1

This will produce following result:

1
2
3
4
5

Jump Statements
The jump statements are used to jump on a specific statement by breaking the current
flow of the program. In Python, there are two jump statements break and continue.

The break Statement


It terminates the current loop and resumes execution at the next statement.

Example
The following example demonstrates the use of break statement −

x = 0

180
Python Tutorial

while x < 10:


print("x:", x)
if x == 5:
print("Breaking...")
break
x += 1

print("End")

This will produce following result:

x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End

The continue Statement


It skips the execution of the program block and returns the control to the beginning of
the current loop to start the next iteration.

Example
The following example demonstrates the use of continue statement −

for letter in "Python":


# continue when letter is 'h'
if letter == "h":
continue
print("Current Letter :", letter)

This will produce following result:

Current Letter : P
Current Letter : y
Current Letter : t

181
Python Tutorial

Current Letter : o
Current Letter : n

182
30. Python - Decision Making Python Tutorial

Python's decision making functionality is in its keywords − if..elif...else. The if keyword


requires a boolean expression, followed by colon (:) symbol. The colon (:) symbol starts
an indented block. The statements with the same level of indentation are executed if the
boolean expression in if statement is True. If the expression is not True (False), the
interpreter bypasses the indented block and proceeds to execute statements at earlier
indentation level.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as


outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages −

Python programming language assumes any non-zero and non-null values as TRUE, and
if it is either zero or null, then it is assumed as FALSE value.

Types of Decision Making Statements in Python


Python programming language provides following types of decision making statements.
Click the following links to check their detail.

[Link]. Statement & Description


1 if statements

183
Python Tutorial

An if statement consists of a boolean


expression followed by one or more
statements.
if...else statements

2 An if statement can be followed by an


optional else statement, which executes
when the boolean expression is FALSE.
nested if statements
3 You can use one if or else if statement
inside another if or else if statement(s).

Let us go through each decision making briefly −

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.

Example
Here is an example of a one-line if clause −

var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")

When the above code is executed, it produces the following result −

Value of expression is 100


Good bye!

if...else statement
In this decision making statement, if the if condition is true, then the statements within
this block are executed, otherwise, the else block is executed.

The program will choose which block of code to execute based on whether the condition
in the if statement is true or false.

Example
The following example shows the use of if...else statement.

var = 100
if ( var == 100 ):
print ("Value of var is equal to 100")

184
Python Tutorial

else:
print("Value of var is not equal to 100")

On running the above code, it will show the following output −

Value of var is equal to 100

Nested if statements
A nested if is another decision making statement in which one if statement resides inside
another. It allows us to check multiple conditions sequentially.

Example
In this example, we will see the use of nested-if statement.

var = 100
if ( var == 100 ):
print("The number is equal to 100")
if var % 2 == 0:
print("The number is even")
else:
print("The given number is odd")
elif var == 0:
print("The given number is zero")
else:
print("The given number is negative")

On executing the above code, it will display the below output −

The number is equal to 100


The number is even

185
31. Python - if Statement Python Tutorial

Python If Statement
The if statement in Python evaluates whether a condition is true or false. It contains a
logical expression that compares data, and a decision is made based on the result of the
comparison.

Syntax of the if Statement


if expression:
# statement(s) to be executed

If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is
executed. If boolean expression evaluates to FALSE, then the first set of code after the
end of the if block is executed.

Flow Diagram (Flowchart) of the if Statement


The below diagram shows flowchart of the if statement −

Example of Python if Statement


Let us consider an example of a customer entitled to 10% discount if his purchase
amount is > 1000; if not, then no discount is applicable. The following flowchart shows
the whole decision making process −

186
Python Tutorial

First, set a discount variable to 0 and an amount variable to 1200. Then, use an if
statement to check whether the amount is greater than 1000. If this condition is true,
calculate the discount amount. If a discount is applicable, deduct it from the original
amount.

Python code for the above flowchart can be written as follows −

discount = 0
amount = 1200

# Check he amount value


if amount > 1000:
discount = amount * 10 / 100

print("amount = ", amount - discount)

187
Python Tutorial

Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will
get the following output −

amount = 1080.0

Change the variable amount to 800, and run the code again. This time, no discount is
applicable. And, you will get the following output −

amount = 800

188
32. Python if-else Statement Python Tutorial

Python if else Statement

The if-else statement in Python is used to execute a block of code when the condition in
the if statement is true, and another block of code when the condition is false.

Syntax of if-else Statement


The syntax of an if-else statement in Python is as follows −

if boolean_expression:
# code block to be executed
# when boolean_expression is true
else:
# code block to be executed
# when boolean_expression is false

If the boolean expression evaluates to TRUE, then the statement(s) inside the if block
will be executed otherwise statements of the else block will be executed.

Flowchart of if-else Statement


This flowchart shows how if-else statement is used −

189
Python Tutorial

If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with
stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the default flow
continues.

Python implementation of the above flowchart is as follows −

if expr==True:
stmt1
stmt2
stmt3
else:
stmt4
stmt5
stmt6
Stmt7

Python if-else Statement Example


Let us understand the use of if-else statements with the following example. Here,
variable age can take different values. If the expression age > 18 is true, then eligible to
vote message will be displayed otherwise not eligible to vote message will be displayed.
Following flowchart illustrates this logic −

190
Python Tutorial

Now, let's see the Python implementation the above flowchart.

age=25
print ("age: ", age)
if age >=18:
print ("eligible to vote")
else:
print ("not eligible to vote")

On executing this code, you will get the following output −

age: 25
eligible to vote

To test the else block, change the age to 12, and run the code again.

age: 12
not eligible to vote

Python if elif else Statement


The if elif else statement allows you to check multiple expressions for TRUE and execute
a block of code as soon as one of the conditions evaluates to TRUE.

Similar to the else block, the elif block is also optional. However, a program can contain
only one else block whereas there can be an arbitrary number of elif blocks following an
if block.

191
Python Tutorial

Syntax of Python if elif else Statement


if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

How if elif else Works?


The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade
of elif statements after the first if statement. If the first if statement evaluates to false,
subsequent elif statements are evaluated one by one and comes out of the cascade if
any one is satisfied.

Last in the cascade is the else block which will come in picture when all preceding if/elif
conditions fails.

Example
Suppose there are different slabs of discount on a purchase −

 20% on amount exceeding 10000,


 10% for amount between 5-10000,
 5% if it is between 1 to 5000.
 no discount if amount<1000

The following flowchart illustrates these conditions −

192
Python Tutorial

We can write a Python code for the above logic with if-else statements −

amount = 2500
print('Amount = ',amount)
if amount > 10000:
discount = amount * 20 / 100
else:
if amount > 5000:
discount = amount * 10 / 100
else:
if amount > 1000:
discount = amount * 5 / 100
else:
discount = 0

print('Payable amount = ',amount - discount)

Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will
vary accordingly −

Amount: 800
Payable amount = 800
Amount: 2500

193
Python Tutorial

Payable amount = 2375.0


Amount: 7500
Payable amount = 6750.0
Amount: 15000
Payable amount = 12000.0

While the code will work perfectly fine, if you look at the increasing level of indentation
at each if and else statement, it will become difficult to manage if there are still more
conditions.

Python if elif else Statement Example


The elif statement makes the code easy to read and comprehend. Following is the
Python code for the same logic with if elif else statements −

amount = 2500
print('Amount = ',amount)
if amount > 10000:
discount = amount * 20 / 100
elif amount > 5000:
discount = amount * 10 / 100
elif amount > 1000:
discount = amount * 5 / 100
else:
discount=0

print('Payable amount = ',amount - discount)

The output of the above code is as follows −

Amount: 2500
Payable amount = 2375.0

194
33. Python - Nested if StatementPython Tutorial

Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement.
There may be a situation when you want to check for additional conditions after the initial
one resolves to true. In such a situation, you can use the nested if construct.
Additionally, within a nested if construct, you can include an if...elif...else construct inside
another if...elif...else construct.

Syntax of Nested if Statement


The syntax of the nested if construct with else condition will be like this −

if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)

Flowchart of Nested if Statement


Following is the flowchart of Python nested if statement −

Example of Nested if Statement


The below example shows the working of nested if statements −

195
Python Tutorial

num = 36
print ("num = ", num)
if num % 2 == 0:
if num % 3 == 0:
print ("Divisible by 3 and 2")
print("....execution ends....")

When you run the above code, it will display the following result −

num = 36
Divisible by 3 and 2
....execution ends....

Nested if Statement with else Condition


As mentioned earlier, we can nest if-else statement within an if statement. If the if
condition is true, the first if-else statement will be executed otherwise, statements inside
the else block will be executed.

Syntax
The syntax of the nested if construct with else condition will be like this −

if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)

Example
Now let's take a Python code to understand how it works −

num=8
print ("num = ",num)
if num%2==0:
if num%3==0:

196
Python Tutorial

print ("Divisible by 3 and 2")


else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

When the above code is executed, it produces the following output −

num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3

197
34. Python - Match-Case Statement
Python Tutorial

Python match-case Statement


A Python match-case statement takes an expression and compares its value to successive
patterns given as one or more case blocks. Only the first pattern that matches gets
executed. It is also possible to extract components (sequence elements or object
attributes) from the value into variables.
With the release of Python 3.10, a pattern matching technique called match-case has been
introduced, which is similar to the switch-case construct available in C/C++/Java etc. Its
basic use is to compare a variable against one or more values. It is more similar to pattern
matching in languages like Rust or Haskell than a switch statement in C or C++.

Syntax
The following is the syntax of match-case statement in Python -

match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2
...
case 'pattern n' : statement n

Example
The following code has a function named weekday(). It receives an integer argument,
matches it with all possible weekday number values, and returns the corresponding name
of day.

def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
print (weekday(7))

198
Python Tutorial

On executing, this code will produce the following output −

Thursday
Sunday
Invalid day number

The last case statement in the function has "_" as the value to compare. It serves as the
wildcard case, and will be executed if all other cases are not true.

Combined Cases in Match Statement


Sometimes, there may be a situation where for more than one cases, a similar action has
to be taken. For this, you can combine cases with the OR operator represented by "|"
symbol.
Example
The code below shows how to combine cases in match statement. It defines a function
named access() and has one string argument, representing the name of the user. For
admin or manager user, the system grants full access; for Guest, the access is limited;
and for the rest, there's no access.

def access(user):
match user:
case "admin" | "manager": return "Full access"
case "Guest": return "Limited access"
case _: return "No access"
print (access("manager"))
print (access("Guest"))
print (access("Ravi"))

On running the above code, it will show the following result −

Full access
Limited access
No access

List as the Argument in Match Case Statement


Since Python can match the expression against any literal, you can use a list as a case
value. Moreover, for variable number of items in the list, they can be parsed to a sequence
with "*" operator.
Example
In this code, we use list as argument in match case statement.

def greeting(details):
match details:
case [time, name]:

199
Python Tutorial

return f'Good {time} {name}!'


case [time, *names]:
msg=''
for name in names:
msg+=f'Good {time} {name}!\n'
return msg

print (greeting(["Morning", "Ravi"]))


print (greeting(["Afternoon","Guest"]))
print (greeting(["Evening", "Kajal", "Praveen", "Lata"]))

On executing, this code will produce the following output −

Good Morning Ravi!


Good Afternoon Guest!
Good Evening Kajal!
Good Evening Praveen!
Good Evening Lata!

Using "if" in "Case" Clause


Normally Python matches an expression against literal cases. However, it allows you to
include if statement in the case clause for conditional computation of match variable.
Example
In the following example, the function argument is a list of amount and duration, and the
intereset is to be calculated for amount less than or more than 10000. The condition is
included in the case clause.

def intr(details):
match details:
case [amt, duration] if amt<10000:
return amt*10*duration/100
case [amt, duration] if amt>=10000:
return amt*15*duration/100
print ("Interest = ", intr([5000,5]))
print ("Interest = ", intr([15000,3]))

On executing, this code will produce the following output −

Interest = 2500.0
Interest = 6750.0

200
35. Python - Loops Python Tutorial

Python Loops
Python loops allow us to execute a statement or a group of statements multiple times.
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.

Flowchart of a Loop
The following diagram illustrates a loop statement −

Types of Loops in Python


Python programming language provides following types of loops to handle looping
requirements −

[Link]. Loop Type & Description


while loop
Repeats a statement or group of
1 statements while a given condition is
TRUE. It tests the condition before
executing the loop body.
2 for loop

201
Python Tutorial

Executes a sequence of statements


multiple times and abbreviates the code
that manages the loop variable.
nested loops
3 You can use one or more loop inside any
another while, for or do..while loop.

Python Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

[Link]. Control Statement & Description


break statement

1 Terminates the loop statement and transfers execution to the


statement immediately following the loop.

continue statement

2 Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

pass statement

3 The pass statement in Python is used when a statement is required


syntactically but you do not want any command or code to
execute.

202
36. Python - For Loops Python Tutorial

The for loop in Python provides the ability to loop over the items of any sequence, such as
a list, tuple or a string. It performs the same action on each item of the sequence. This
loop starts with the for keyword, followed by a variable that represents the current item
in the sequence.
The in keyword links the variable to the sequence you want to iterate over. A colon (:) is
used at the end of the loop header, and the indented block of code beneath it is executed
once for each item in the sequence.

Syntax of Python for Loop


for iterating_var in sequence:
statement(s)

Here, the iterating_var is a variable to which the value of each sequence item will be
assigned during each iteration. Statements represents the block of code that you want to
execute repeatedly.
Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if any)
is evaluated first. Then, the first item (at index 0) in the sequence is assigned to
iterating_var variable.
During each iteration, the block of statements is executed with the current value of
iterating_var. After that, the next item in the sequence is assigned to iterating_var, and
the loop continues until the entire sequence is exhausted.

Flowchart of Python for Loop


The following flow diagram illustrates the working of for loop −

Python for Loop with Strings


A string is a sequence of Unicode letters, each having a positional index. Since, it is a
sequence, you can iterate over its characters using the for loop.

203
Python Tutorial

Example
The following example compares each character and displays if it is not a vowel ('a', 'e',
'i', 'o', 'u').

zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print (char, end='')

On executing, this code will produce the following output −

Btfl s bttr thn gly.


Explct s bttr thn mplct.
Smpl s bttr thn cmplx.
Cmplx s bttr thn cmplctd.

Python for Loop with Tuples


Python's tuple object is also an indexed sequence, and hence you can traverse its items
with a for loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns
the total of all numbers.

numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)

On running this code, it will produce the following output −

Total = 539

Python for Loop with Lists


Python's list object is also an indexed sequence, and hence you can iterate over its items
using a for loop.
Example

204
Python Tutorial

In the following example, the for loop traverses a list containing integers and prints only
those which are divisible by 2.

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
if num%2 == 0:
print (num)

When you execute this code, it will show the following result −

34
54
78
44
80

Python for Loop with Range Objects


Python's built-in range() function returns an iterator object that streams a sequence of
numbers. This object contains integers from start to stop, separated by step parameter.
You can run a for loop with range as well.

Syntax
The range() function has the following syntax −

range(start, stop, step)

Where,
 Start − Starting value of the range. Optional. Default is 0
 Stop − The range goes upto stop-1
 Step − Integers in the range increment by the step value. The default is 1.
Example
In this example, we will see the use of range with for loop.

for num in range(5):


print (num, end=' ')
print()
for num in range(10, 20):
print (num, end=' ')
print()
for num in range(1, 10, 2):
print (num, end=' ')

When you run the above code, it will produce the following output −

205
Python Tutorial

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

Python for Loop with Dictionaries


Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the
items do not have a positional index. However, traversing a dictionary is still possible with
the for loop.
Example
Running a simple for loop over the dictionary object traverses the keys used in it.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x)

On executing, this code will produce the following output −

10
20
30
40

Once we are able to get the key, its associated value can be easily accessed either by
using square brackets operator or with the get() method.
Example
The following example illustrates the above mentioned approach.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x,":",numbers[x])

It will produce the following output −

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

The items(), keys() and values() methods of dict class return the view objects dict_items,
dict_keys and dict_values respectively. These objects are iterators, and hence we can run
a for loop over them.

Example

206
Python Tutorial

The dict_items object is a list of key-value tuples over which a for loop can be run as
follows −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in [Link]():
print (x)

It will produce the following output −

(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')

Using else Statement with For Loop


Python supports else statements associated with a loop statement. However, the else
statement is executed when the loop has exhausted iterating the list.
Example
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 to 20.

#For loop to iterate between 10 to 20


for num in range(10, 20):
#For loop to iterate on the factors
for i in range(2,num):
#If statement to determine the first factor
if num%i == 0:
#To calculate the second factor
j=num/i
print ("%d equals %d * %d" % (num,i,j))
#To move to the next number
break
else:
print (num, "is a prime number")
break

When the above code is executed, it produces the following result −

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number

207
Python Tutorial

14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

208
37. Python for-else Loops Python Tutorial

Python - For Else Loop


Python supports an optional else block to be associated with a for loop. If a else block is
used with a for loop, it is executed only when the for loop terminates normally.
The for loop terminates normally when it completes all its iterations without encountering
a break statement, which allows us to exit the loop when a certain condition is met.

Flowchart of For Else Loop


The following flowchart illustrates use of for-else loop −

Syntax of For Else Loop


Following is the syntax of for loop with optional else block −

for variable_name in iterable:


#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.

Example of For Else Loop

209
Python Tutorial

The following example illustrates the combination of an else statement with a for
statement in Python. Till the count is less than 5, the iteration count is printed. As it
becomes 5, the print statement in else block is executed, before the control is passed to
the next statement in the main program.

for count in range(6):


print ("Iteration no. {}".format(count))
else:
print ("for loop over. Now in else block")
print ("End of for loop")

On executing, this code will produce the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
for loop over. Now in else block
End of for loop

For-Else Construct without break statement


As mentioned earlier in this tutorial, the else block executes only when the loop terminates
normally i.e. without using break statement.
In the following program, we use the for-else loop without break statement.

for i in ['T','P']:
print(i)
else:
# Loop else statement
# there is no break statement in for loop, hence else part gets executed
directly
print("ForLoop-else statement successfully executed")

On executing, the above program will generate the following output −

T
P
ForLoop-else statement successfully executed

210
Python Tutorial

For-Else Construct with break statement


In case of forceful termination (by using break statement) of the loop, else statement is
overlooked by the interpreter and hence its execution is skipped.
Example
The following program shows how else conditions work in case of a break statement.

for i in ['T','P']:
print(i)
break
else:
# Loop else statement
# terminated after 1st iteration due to break statement in for loop
print("Loop-else statement successfully executed")

On executing, the above program will generate the following output −

For-Else with break statement and if conditions


If we use for-else construct with break statement and if condition, the for loop will iterate
over the iterators and within this loop, you can use an if block to check for a specific
condition. If the loop completes without encountering a break statement, the code in the
else block is executed.
Example
The following program shows how else conditions works in case of break statement and
conditional statements.

# creating a function to check whether the list item is a positive


# or a negative number
def positive_or_negative():
# traversing in a list
for i in [5,6,7]:
# checking whether the list element is greater than 0
if i>=0:
# printing positive number if it is greater than or equal to 0
print ("Positive number")
else:
# Else printing Negative number and breaking the loop
print ("Negative number")
break
# Else statement of the for loop

211
Python Tutorial

else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()

On executing, the above program will generate the following output −

Positive number
Positive number
Positive number
Loop-else Executed

212
38. Python - While Loops Python Tutorial

Python while Loop


A while loop in Python programming language repeatedly executes a target statement as
long as the specified boolean expression is true. This loop starts with while keyword
followed by a boolean expression and colon symbol (:). Then, an indented block of
statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform
indent. The condition may be any expression, and true is any non-zero value. As soon as
the expression becomes false, the program control passes to the line immediately following
the loop.
If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped.
Such a loop is called infinite loop, which is undesired in a computer program.

Syntax of while Loop


The syntax of a while loop in Python programming language is −

while expression:
statement(s)

In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

Flowchart of While loop


The following flow diagram illustrates the while loop −

Example 1
The following example illustrates the working of while loop. Here, the iteration run till value
of count will become 5.

count=0

213
Python Tutorial

while count<5:
count+=1
print ("Iteration no. {}".format(count))

print ("End of while loop")

On executing, this code will produce the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
End of while loop

Example 2
Here is another example of using the while loop. For each iteration, the program asks for
user input and keeps repeating till the user inputs a non-numeric string. The isnumeric()
function returns true if input is an integer, false otherwise.

var = '0'
while [Link]() == True:
var = "test"
if [Link]() == True:
print ("Your input", var)
print ("End of while loop")

On running the code, it will produce the following output −

enter a number..10
Your input 10
enter a number..100
Your input 100
enter a number..543
Your input 543
enter a number..qwer
End of while loop

Python Infinite while Loop


A loop becomes infinite if a condition never becomes FALSE. You must be cautious when
using while loops because of the possibility that this condition never resolves to a FALSE
value. This results in a loop that never ends. Such a loop is called an infinite loop.

214
Python Tutorial

An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.
Example
Let's take an example to understand how the infinite loop works in Python −

var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")

On executing, this code will produce the following output −

Enter a number :20


You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\[Link]", line 5, in
num = int(input("Enter a number :"))
KeyboardInterrupt

The above example goes in an infinite loop and you need to use CTRL+C to exit
the program.

Python while-else Loop


Python supports having an else statement associated with a while loop. If the else
statement is used with a while loop, the else statement is executed when the condition
becomes false before the control shifts to the main line of execution.

Flowchart of While loop with else Statement


The following flow diagram shows how to use else statement with while loop −

215
Python Tutorial

Example
The following example illustrates the combination of an else statement with a while
statement. Till the count is less than 5, the iteration count is printed. As it becomes 5, the
print statement in else block is executed, before the control is passed to the next statement
in the main program.

count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))
else:
print ("While loop over. Now in else block")
print ("End of while loop")

On running the above code, it will print the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
While loop over. Now in else block
End of while loop

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single statement,
it may be placed on the same line as the while header.
Example
The following example shows how to use one-line while clause.

flag = 0
while (flag): print ("Given flag is really true!")

216
Python Tutorial

print ("Good bye!")

When you run this code, it will display the following output −

Good bye!

Change the flag value to "1" and try the above program. If you do so, it goes into infinite
loop and you need to press CTRL+C keys to exit.

217
39. Python - break Statement Python Tutorial

Python break Statement


Python break statement is used to terminate the current loop and resumes execution at
the next statement, just like the traditional break statement in C.
The most common use for Python break statement is when some external condition is
triggered requiring a sudden exit from a loop. The break statement can be used in both
Python while and for loops.
If you are using nested loops in Python, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.

Syntax of break Statement


The syntax for a break statement in Python is as follows −

looping statement:
condition check:
break

Flow Diagram of break Statement


Following is the flowchart of the break statement −

break Statement with for loop


If we use break statement inside a for loop, it interrupts the normal flow of program and
exit the loop before completing the iteration.

218
Python Tutorial

Example
In this example, we will see the working of break statement in for loop.

for letter in 'Python':


if letter == 'h':
break
print ("Current Letter :", letter)
print ("Good bye!")

When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y
Current Letter : t
Good bye!
break Statement with while loop

Similar to the for loop, we can use the break statement to skip the code inside while loop
after the specified condition becomes TRUE.
Example
The code below shows how to use break statement with while loop.

var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break

print ("Good bye!")

On executing the above code, it produces the following result −

Current variable value : 10


Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

219
Python Tutorial

break Statement with Nested Loops


In nested loops, one loop is defined inside another. The loop that enclose another loop
(i.e. inner loop) is called as outer loop.
When we use a break statement with nested loops, it behaves as follows −
When break statement is used inside the inner loop, only the inner loop will be skipped
and the program will continue executing statements after the inner loop
And, when the break statement is used in the outer loop, both the outer and inner loops
will be skipped and the program will continue executing statements immediate to the outer
loop.
Example
The following program demonstrates the use of break in a for loop iterating over a list.
Here, the specified number will be searched in the list. If it is found, then the loop
terminates with the "found" message.

no = 33
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num == no:
print ('number found in list')
break
else:
print ('number not found in list')

The above program will produce the following output −

number found in list

220
40. Python - Continue StatementPython Tutorial

Python continue Statement


Python continue statement is used to skip the execution of the program block and returns
the control to the beginning of the current loop to start the next iteration. When
encountered, the loop starts next iteration without executing the remaining statements in
the current iteration.
The continue statement is just the opposite to that of break. It skips the remaining
statements in the current loop and starts the next iteration.

Syntax of continue Statement


looping statement:
condition check:
continue

Flow Diagram of continue Statement


The flow diagram of the continue statement looks like this −

Python continue Statement with for Loop


In Python, the continue statement is allowed to be used with a for loop. Inside the for
loop, you should include an if statement to check for a specific condition. If the condition
becomes TRUE, the continue statement will skip the current iteration and proceed with the
next iteration of the loop.
Example
Let's see an example to understand how the continue statement works in for loop.

221
Python Tutorial

for letter in 'Python':


if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following output −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!

Python continue Statement with while Loop


Python continue statement is used with 'for' loops as well as 'while' loops to skip the
execution of the current iteration and transfer the program's control to the next iteration.
Example: Checking Prime Factors
Following code uses continue statement to find the prime factors of a given number. To
find prime factors, we need to successively divide the given number starting with 2,
increment the divisor and continue the same process till the input reduces to 1.

num = 60
print ("Prime factors for: ", num)
d=2
while num > 1:
if num%d==0:
print (d)
num=num/d
continue
d=d+1

On executing, this code will produce the following output −

Prime factors for: 60


2
2
3
5

222
Python Tutorial

Assign different value (say 75) to num in the above program and test the result for its
prime factors.

Prime factors for: 75


3
5
5

223
41. Python - pass Statement Python Tutorial

Python pass Statement


Python pass statement is used when a statement is required syntactically but you do not
want any command or code to execute. It is a null which means nothing happens when it
executes. This is also useful in places where piece of code will be added later, but a
placeholder is required to ensure the program runs without errors.
For instance, in a function or class definition where the implementation is yet to be written,
pass statement can be used to avoid the SyntaxError. Additionally, it can also serve as a
placeholder in control flow statements like for and while loops.

Syntax of pass Statement


Following is the syntax of Python pass statement −

pass

Example of pass Statement


The following code shows how you can use the pass statement in Python −

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following output −

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Dumpy Infinite Loop with pass Statement


This is simple enough to create an infinite loop using pass statement in Python.
Example

224
Python Tutorial

If you want to code an infinite loop that does nothing each time through, do it as shown
below −

while True: pass


# Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop.

Using Ellipses (...) as pass Statement Alternative


Python 3.X allows ellipses (coded as three consecutive dots ...) to be used in place of pass
statement. Both serve as placeholders for code that are going to be written later.
Example
For example if we create a function which does not do anything especially for code to be
filled in later, then we can make use of ...

def func1():
# Alternative to pass
...

# Works on same line too


def func2(): ...
# Does nothing if called
func1()
func2()

225
42. Python - Nested Loops Python Tutorial

In Python, when you write one or more loops within a loop statement that is known as a
nested loop. The main loop is considered as outer loop and loop(s) inside the outer loop
are known as inner loops.
The Python programming language allows the usage of one loop inside another loop. A
loop is a code block that executes specific instructions repeatedly. There are two types of
loops, namely for and while, using which we can create nested loops.

You can put any type of loop inside of any other type of loop. For example, a
for loop can be inside a while loop or vice versa.

Python Nested for Loop


The for loop with one or more inner for loops is called nested for loop. A for loop is used
to loop over the items of any sequence, such as a list, tuple or a string and performs the
same action on each item of the sequence.

Python Nested for Loop Syntax


The syntax for a Python nested for loop statement in Python programming language is as
follows −

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

Python Nested for Loop Example


The following program uses a nested for loop to iterate over months and days lists.

months = ["jan", "feb", "mar"]


days = ["sun", "mon", "tue"]

for x in months:
for y in days:
print(x, y)

print("Good bye!")

When the above code is executed, it produces following result −

jan sun
jan mon

226
Python Tutorial

jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Good bye!

Python Nested while Loop


The while loop having one or more inner while loops are nested while loop. A while loop is
used to repeat a block of code for an unknown number of times until the specified boolean
expression becomes TRUE.

Python Nested while Loop Syntax


The syntax for a nested while loop statement in Python programming language is as follows

while expression:
while expression:
statement(s)
statement(s)

Python Nested while Loop Example


The following program uses a nested while loop to find the prime numbers from 2 to 100

i = 2
while(i < 25):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print (i, " is prime")
i = i + 1

print ("Good bye!")

On executing, the above code produces following result −

2 is prime
3 is prime
227
Python Tutorial

5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
Good bye!

228

You might also like