Control Statements
Control Statements
<<< 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'>
<<< 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.
<<< a = int("110011", 2)
<<< a
77
Python Tutorial
51
<<< a = int("20", 8)
<<< a
16
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)
1
2
3
<<< 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'
<<< 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:
print (a)
print (b)
print (c)
1.0
2.2
3.3
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'>
<<< 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:
print (a)
print (b)
print (c)
1
2.2
3.3
### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']
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')
### 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.
83
Python Tutorial
84
14. Python - Unicode System Python Tutorial
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.
Example
var = "3/4"
print (var)
var = "\u00BE"
print (var)
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)
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
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)
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
When you run this code, it will produce the following output −
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
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))
L1=[1,"Ravi",75.50, True]
91
Python Tutorial
T1=(1,"Ravi",75.50, True)
print (T1, type(T1))
T1=1,"Ravi",75.50, True
print (T1, type(T1))
92
Python Tutorial
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,
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.
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
94
Python Tutorial
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
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
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
97
Python Tutorial
|= a |= 5 a=a|5
^= a ^= 5 a=a^5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5
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
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
or OR a or b
var = 5
Output
True
True
False
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 −
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
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
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
103
17. Python - Arithmetic OperatorsPython Tutorial
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)
104
Python Tutorial
a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)
a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)
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 −
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)
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)
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)
106
Python Tutorial
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)
a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)
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
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)
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)
108
Python Tutorial
a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)
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
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
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)
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)
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
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)
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
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)
For example,
a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j
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)
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
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
a=5
b=7
print (a>b)
print (a<b)
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
116
Python Tutorial
Example
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
117
Python Tutorial
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
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)
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
119
Python Tutorial
120
19. Python - Assignment Operators
Python Tutorial
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".
121
Python Tutorial
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'>
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))
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))
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))
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))
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))
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
127
20. Python - Logical Operators Python Tutorial
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.
a b a and b
F F F
F T F
T F F
T T T
a b a or b
F F F
F T T
T F T
T T T
128
Python Tutorial
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.
129
Python Tutorial
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)
x and y: 20
x or y: 10
z or x: 10
y or z: 20
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)
a and b: ()
b or a: Hello
x=[1,2,3]
y=[10,20,30]
print("x and y:",x and y)
print("x or y:",x or y)
131
21. Python - Bitwise Operators Python Tutorial
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)
a: 60 b: 13 a&b: 12
To understand how Python performs the operation, obtain the binary equivalent of each
variable.
132
Python Tutorial
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
0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1
a=60
b=13
print ("a:",a, "b:",b, "a|b:",a|b)
print ("a:", bin(a))
print ("b:", bin(b))
a: 60 b: 13 a|b: 61
a: 0b111100
133
Python Tutorial
b: 0b1101
0011 1100
|
0000 1101
-------------
0011 1101
>>> int('00111101',2)
61
0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0
a=60
b=13
print ("a:",a, "b:",b, "a^b:",a^b)
a: 60 b: 13 a^b: 49
0011 1100
^
0000 1101
-------------
0011 0001
>>> int('00110001',2)
49
134
Python Tutorial
a=60
print ("a:",a, "~a:", ~a)
a: 60 ~a: -61
a=60
print ("a:",a, "a<<2:", a<<2)
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
>>> int('11110000',2)
240
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)
a: 60 a>>2: 15
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
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)
P in TutorialsPoint : True
tor in TutorialsPoint : True
in in TutorialsPoint : True
To in TutorialsPoint : False
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)
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)
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
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)
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)
139
Python Tutorial
140
23. Python - Identity Operators Python Tutorial
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a
True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456
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
False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176
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)
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)
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
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
>>> 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).
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
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; # 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!")
147
Python Tutorial
number = 5
print(f"The factorial of {number} is {factorial(number)}")
"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm. The GCD of
148
Python Tutorial
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__)
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
#! /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
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.
151
Python Tutorial
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()
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.
152
Python Tutorial
#! /usr/bin/python3.11
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.
#! /usr/bin/python3.11
area = width*height
print ("Area of rectangle = ", area)
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 −
You can combine the input and type cast statements in one −
#! /usr/bin/python3.11
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
interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)
The program ask user to enter amount and rate; and displays the result as follows −
154
Python Tutorial
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.
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
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)
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"
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.
>>> a =10
a = 10
b = 20
c = a + b
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")
a=0b101
print ("a:",a, "type:",type(a))
b=int("0b101011", 2)
print ("b:",b, "type:",type(b))
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)
a=0O107
print (a, type(a))
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))
16 <class 'int'>
a=0O56
print ("a:",a, "type:",type(a))
b=int("0O31",8)
print ("b:",b, "type:",type(b))
c=a+b
print ("addition:", c)
a=oct(71)
print (a, type(a))
a=0XA2
print (a, type(a))
159
Python Tutorial
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)
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))
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))
a=10 #decimal
b=0b10 #binary
c=0O10 #octal
d=0XA #Hexadecimal
e=a+b+c+d
160
Python Tutorial
print ("addition:", e)
addition: 30
>>> 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
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)
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)
a= -123.54 b= 12300.0
a=1.00E400
print (a, type(a))
a=float("Infinity")
162
Python Tutorial
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
>>> 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))
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))
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))
164
Python Tutorial
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)
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])
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)
165
Python Tutorial
[Link](n,k)
[Link](x, y)
[Link](x, y)
[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)
[Link](x)
[Link](iterable)
10 This function returns the floating point sum of all numeric items in
an iterable i.e. list, tuple, array.
[Link](*integers)
[Link]()
13 [Link](x)
166
Python Tutorial
[Link](x)
[Link](x)
15 This function is used to determine whether the given number is
"NaN".
[Link](n)
[Link](*integers)
[Link](x, i)
[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)
[Link](iterable, *, start)
[Link](x,y)
24 [Link](x)
167
Python Tutorial
[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.
[Link](x)
2
This function calculate the exponential of x: ex
math.exp2(x)
math.expm1(x)
[Link](x)
math.log1p(x)
math.log2(x)
8 math.log10(x)
168
Python Tutorial
[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](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).
2 [Link](x)
169
Python Tutorial
Mathematical Constants
The Python math module defines the following mathematical constants −
good.e
math. number
[Link]
math. in
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 −
2 [Link](x)
170
Python Tutorial
[Link](x)
[Link](x)
[Link](x)
[Link](x)
Special Functions
Following are the special functions provided by the Python math module −
[Link](x)
[Link](x)
[Link](x)
171
Python Tutorial
[Link]([x])
[Link](seq)
[Link](a, b)
172
Python Tutorial
173
28. Python - Booleans Python Tutorial
>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)
a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)
bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)
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
176
29. Python - Control Flow Python Tutorial
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.
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)
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'))
Vowel alphabet
178
Python Tutorial
Simple alphabet
Vowel alphabet
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.
Example
Following is an example which makes use of For Loop to iterate through an array in
Python:
179
Python Tutorial
print(x)
one
two
three
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
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.
Example
The following example demonstrates the use of break statement −
x = 0
180
Python Tutorial
print("End")
x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End
Example
The following example demonstrates the use of continue statement −
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
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.
183
Python Tutorial
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!")
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")
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")
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.
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.
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.
discount = 0
amount = 1200
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
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.
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.
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.
if expr==True:
stmt1
stmt2
stmt3
else:
stmt4
stmt5
stmt6
Stmt7
190
Python Tutorial
age=25
print ("age: ", age)
if age >=18:
print ("eligible to vote")
else:
print ("not eligible to vote")
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
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
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 −
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
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
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.
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
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.
if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)
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....
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
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
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
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.
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"))
Full access
Limited access
No access
def greeting(details):
match details:
case [time, name]:
199
Python Tutorial
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]))
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 −
201
Python Tutorial
continue statement
2 Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
pass statement
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.
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.
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='')
numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)
Total = 539
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
Syntax
The range() function has the following syntax −
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.
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
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.
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 −
(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')
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
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.
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 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")
T
P
ForLoop-else statement successfully executed
210
Python Tutorial
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")
211
Python Tutorial
else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()
Positive number
Positive number
Positive number
Loop-else Executed
212
38. Python - While Loops Python Tutorial
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.
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))
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")
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
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!")
The above example goes in an infinite loop and you need to use CTRL+C to exit
the program.
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")
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
flag = 0
while (flag): print ("Given flag is really true!")
216
Python Tutorial
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
looping statement:
condition check:
break
218
Python Tutorial
Example
In this example, we will see the working of break statement in for loop.
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
219
Python Tutorial
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')
220
40. Python - Continue StatementPython Tutorial
221
Python Tutorial
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!
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
222
Python Tutorial
Assign different value (say 75) to num in the above program and test the result for its
prime factors.
223
41. Python - pass Statement Python Tutorial
pass
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
224
Python Tutorial
If you want to code an infinite loop that does nothing each time through, do it as shown
below −
Because the body of the loop is just an empty statement, Python gets stuck in this loop.
def func1():
# Alternative to pass
...
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.
for x in months:
for y in days:
print(x, y)
print("Good bye!")
jan sun
jan mon
226
Python Tutorial
jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Good bye!
while expression:
while expression:
statement(s)
statement(s)
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
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