Learn Python Quickly
Learn Python Quickly
QUICKLY
AND
PYTHON CODING
EXERCISES
1
LEARN PYTHON QUICKLY
Install python on MAC OS
Python: Hello World program
Python interactive command line
Python: Operators
Arithmetic Operators in python
Relational Operators in python
Assignment operators in python
Logical Operators in python
Bitwise Operators in python
Membership operators in python
Identity operators in python
Python: Short circuit operators
Strings in python
Python: if condition
Python: while statement
Python: for statement
Python: break statement
Python: continue statement
Python: functions
Python: functions: return statement
Python lists
Python: tuples
Python: Sets
Python modules
Python command line arguments
Python: File handling
Python: classes and objects
Python: Class Vs Instance variables
Python: Inheritance
Python: Exceptions
2
Python: Handling Exceptions
Python global keyword
Python: Get type of variable
Python Basic – Exercises
Get Python version
Display current date and time
Print the calendar
Computes the value of n+nn+nnn
Calculate number of days
volume of a sphere in Python
Compute the area of Triangle
Compute the GCD
Calculate The LCM
Convert feet and inches to centimeters
Convert time – seconds
Convert seconds to day
Calculate BMS
Sort three integers
Get system time
Check a number
Python code to Remove first item
Filter positive numbers
Count the number 4
Find a number even or odd
Get n copies of a given string
Print out a list which are not present in other list
Display details name, age, address in three
different lines
Program to solve
Future value of amount
Check whether a file exists
Convert the distance
3
Sum all the items
Multiplies all the items
Get the largest number
Get the smallest number
Remove duplicates
Clone or copy a list
Difference between the two lists
Generate all permutations
Find the second smallest
Get unique values
Get the frequency of the elements
Generate all sublists
Find common items
Create a list
Remove consecutive duplicates
Flatten a nested
4
LEARN PYTHON
QUICKLY
5
LEARN PYTHON QUICKLY
Well it is almost 5 years I started my IT career, I love to
work in Java, and explore open source packages. Now a
day I felt bored to work in Java, so want to learn new
language, one of my friend suggested me to learn python.
Immediately I thought, why should I learn python?
6
h. Python has very great community, whatever the
problem you faced in python, you will get quick help.
7
Install python on MAC OS
Step 1: Download python software from following location. I downloaded pkg
file to install on mac os.
https://www.python.org/downloads/
Press Continue.
Press Continue.
8
Accept license agreement and press Continue.
You can change the installation location use the button ‘Change Install
Location’, and press the button Install.
9
Once installation is successful, open terminal and type python3 (Since I
installed python 3.5).
$ python3
Python 3.5 . 0 (v3. 5.0 :374 f501f4567, Sep 12 2015 ,
11 :00 :19 )
[GCC 4.2 . 1 (Apple Inc. build 5666 ) (dot 3 )] on darwin
Type "help" , "copyright" , "credits" or "license" for more
information.
>> > quit()
Location of python3
$ which python3
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
$ which python3.5
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
On windows machines python usually placed at ‘C:\Python35’.
10
Python: Hello World
program
Open any text editor and copy the statement “print ('hello world')” and save
the file name as hello.py.
hello.py
print ('hello world')
Open terminal (or) command prompt, use the command ‘python3 hello.py’ to
run the file hello.py. You will get output like below
$ python3 hello.py
hello world
Note:
Byte code is not machine understandable code, it is python
specific representation.
11
Python interactive command
line
Open command prompt (or) terminal and type
‘python3’ command. It opens python interactive
session.
$ python3
Python 3.5.0 (v3.5.0:374f501f4567, Sep 12 2015,
11:00:19)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more
information.
>>>
12
400
>>> print('Hello World')
Hello World
Note:
On Unix, the Python 3.x interpreter is not installed
by default with name python, so that it does not
conflict with other installed Python 2.x executable.
13
Python: Operators
An operator is a symbol, which perform an operation. Following are the
operators that python supports.
Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
14
Arithmetic Operators in
python
>>> 4 + 2
6
>>> 4 - 2
2
>>> 4 / 2
15
2.0
>>> 4 * 2
8
>>> 4 // 2
2
>>> 4 ** 2
16
Relational Operators in
python
Relational operators determine if one operand is greater than, less than,
equal to, or not equal to another operand.
16
else false.
>>> a = 10
>>> b = 12
>>> a = = b
False
>>> a ! = b
True
>>> a > b
False
>>> a > = b
False
>>> a < b
True
>>> a < = b
True
>>>
Assignment operators in
python
Assignment operators are used to assign value to a variable. Following are
the assignment operators provided by python.
Operat Description
or
= a=10 assigns 10 to variable a
+= a+=10 is same as a=a+10
-= a-=10 is same as a=a-10
*= a*=10 is same as a=a*10
/= a/=10 is same as a=a/10
//= a//=10 is same as a=a//10
17
%= a%=10 is same as a=a%10
**= a**=10 is same as a=a**10
>>> a = 10
>>> a
10
>>>
>>> a += 10
>>> a
20
>>>
>>> a -= 10
>>> a
10
>>>
>>> a *= 10
>>> a
100
>>>
>>> a /= 10
>>> a
10.0
>>>
>>> a //= 10
>>> a
1.0
>>>
>>> a **= 10
>>> a
1.0
Multiple Assignments
You can assign values to multiple variables
simultaneously.
>>> a, b, c = 1 0 , 'hello ' , 12.345
>>> a
10
18
>>> b
'hello'
>>> c
12.345
Logical Operators in
python
Following are the logical operators supported by python.
Operato Description
r
and ‘a and b’ returns true if both a, b are
true. Else false.
or ‘a or b’ return false, if both a and b are
false, else true.
not ‘not a’ Returns True if a is false, true
otherwise
>>> a = bool( 0 )
>>> b = bool( 1 )
>>>
>>> a
False
>>> b
True
>>>
>>> a an d b
False
>>>
>>> a o r b
True
>>>
19
>>> no t a
True
>>>
>>> no t (a an d b)
True
>>>
>>> no t (a o r b)
False
Bitwise Operators in
python
Python supports following bitwise operators, to perform bit wise operations
on integers.
Operator Description
>> bitwise right shift
<< bitwise left shift
& bitwise and
^ Bitwise Ex-OR
| Bitwise or
~ Bitwise not
Following post, explains bitwise operators clearly.
http://self-learning-java-tutorial.blogspot.in/2014/02/bit-wise-operators.html
>>> a = 2
>>> a >> 1
1
>>>
>>> a << 1
4
>>>
>>> a & 3
2
20
>>> a | 3
3
>>>
>>> ~ a
-3
Membership operators in
python
Membership operators are used to test whether a value or variable is found in
a sequence (string, list, tuple, set and dictionary).
Operato Description
r
in Return true if value/variable is found in
the sequence, else false.
not in Return True if value/variable is not
found in the sequence, else false
>>> primeNumbers = [ 2 , 3 , 5 , 7 , 1 1 ]
>>> 2 i n primeNumbers
True
>>> 4 i n primeNumbers
False
>>> 4 no t i n primeNumbers
True
Identity operators in
python
Identity operators are used to compare the memory locations of two objects.
Operat Description
21
or
is a is b returns true, if both a and b point
to the same object, else false.
is not a is not b returns true, if both a and b
not point to the same object, else false.
22
Strings in python
String is a sequence of character specified in single quotes('…'), double
quotes("…"), (or) triple quotes ("""…""" or ''' … '''). Strings in python are
immutable, i.e., an object with a fixed value.
>>> str1 = 'Hello World'
>>> str2 = "Hello World"
>>> str3 = """Hello
... World
... """
>>> str1
'Hello World'
>>> str2
'Hello World'
>>> str3
'Hello\nWorld\n'
As you observe output, \n prints new line. If you don’t want characters
prefaced by \ to be interpreted as special characters, you can use raw strings
by adding an r before the first quote
23
Concatenate strings
'+' operator is used to concatenate strings.
Two or more string literals next to each other are automatically concatenated.
Repeat strings
By using ‘*’, we can repeat the strings.
>>> 'hi' * 2
'hihi'
>>> 'hi' * 2 + 'hello' * 3
'hihihellohellohello'
st nd
Index 0 represents 1 character, 1 represents 2 character etc.,
>>> name
'Hello World'
24
>>> name[ - 1 ]
'd'
>>> name[ - 2 ]
'l'
>>> name[ - 7 ]
'o'
Slicing
Slicing is used to get sub string of given string.
Example Description
string[start:end] Returns sub string from index
start (included) to end index
(excluded).
string[:end] Returns sub string from index
0(included) to end index
(excluded).
string[start:] Return sub string from index
start to till end.
string[-2:] Return characters from 2 nd last
to end.
25
Get length of the string
Function ‘len(str)’ is used to get the length of the
string.
>>> message
'Hello World'
>>> len(message)
11
>>> len( "How are you " )
11
26
Python: if condition
“if” statement
"if" tell the program execute the section of code when the condition
evaluates to true.
Syntax
if_stmt ::= "if" expression ":" suite
test.py
a = 10
if (a < 10 ) :
print ("a is less than 10" )
if (a == 10 ) :
print ("a is equal to 10" )
if ( a > 10 ) :
print ("a is greater than 10" )
$ python3 test.py
a is equal to 10
if-else statement
If the condition true, then if block code executed. other wise else block code
executed.
Syntax
if_stmt ::= "if" expression ":" suite
["else" ":" suite]
test.py
a = 10
if (a != 10 ) :
print ("a is not equal to 10" )
else :
27
print ("a is equal to 10" )
if-elif-else statement
By using if-elif-else construct, you can choose number of alternatives. An if
statement can be followed by an optional elif...else statement.
Syntax
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
test.py
a = 10
if (a > 10 ) :
print ("a is greater than 10" )
elif (a < 10 ) :
print ("a is less than 10" )
else :
print ("a is equal to 10" )
$ python3 test.py
a is equal to 10
Note:
a. In python, any non-zero integer value is treated as true; zero is false.
test.py
if (100 ) :
print ("Hello" )
else :
print ("Bye" )
$ python3 test.py
Hello
28
b. Any sequence (string, list etc.,) with a non-zero length is true, empty
sequences are false.
test.py
list = []
data= "abc"
if (list ) :
print ("list is not empty" )
else :
print ("list is empty" )
if (data) :
print ("data is not empty" )
else :
print ("data is empty" )
$ python3 test.py
list is empty
data is not empty
29
Python: while statement
‘while’ statement executes a block of statements until a particular condition
is true
Syntax
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
‘else’ clause is optional. If the expression evaluates to false, then else clause
will execute (if else present), and terminates.
test.py
a = 2
30
Python: for statement
Python’s for statement is used to iterate over the items of any sequence like
a list, string.
Syntax
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
test.py
names = [ "Phalgun " , "Sambith " , "Mahesh " , "swapna " ]
for name in names:
print (name)
else :
print ("Exiting from loop" )
prin t ( "Finsihed Execution " )
$ python3 test.py
Phalgun
Sambith
Mahesh
swapna
Exiting from loop
Finsihed Execution
31
Python: break statement
'break' statement is used to come out of loop like for, while.
test.py
i = 0
while (1 ):
i+= 2
print (i)
if (i== 10 ):
break
else :
print ("Exiting loop" )
print( "Finished Execution " )
$ python3 test.py
2
4
6
8
10
Finished Execution
As you observe the output, print statement in else clause is not printed. It is
because, else clause will not execute, when a break statement terminates the
loop.
32
Python: continue
statement
‘continue’ statement skips the current iteration of loops like for, while.
test.py
i = 2
while (i < 20 ):
i+= 2
if (i% 2 != 0 ):
continue
print (i)
else :
print ("Exiting loop" )
print( "Finished Execution " )
Above program prints all the even numbers up to 20 (exclusive).
$ python3 test.py
4
6
8
10
12
14
16
18
20
Exiting loop
Finished Execution
33
Python: functions
A function is a block of statements identified by a name. The keyword 'def' is
used to define a function. Functions are mainly used for two reasons.
a . To make code easier to build and understand
b . To reuse the code
Syntax
def functionName(argument1, argument2 …. argumentN):
test.py
def factorial (n):
if (n<= 1 ):
return 1
result = 1
for i in range (2 , n+ 1 ):
result *= i
return result
print(factorial( 1 ))
print(factorial( 2 ))
print(factorial( 3 ))
print(factorial( 4 ))
print(factorial( 5 ))
$ python3 test.py
1
2
6
24
120
34
x = 44
35
Python: functions: return
statement
‘return’ statement is used to return a value from function to the caller.
test.py
for i in range (2 , n+ 1 ):
result *= i
return result
print(factorial( 1 ))
print(factorial( 2 ))
print(factorial( 3 ))
print(factorial( 4 ))
print(factorial( 5 ))
$ python3 test.py
1
2
6
24
120
def hello():
print("Hello")
print(hello())
$ python3 test.py
36
Hello
None
37
Python lists
List is group of values in between square brackets separated by commas.
>>> primes = [ 2 , 3 , 5 , 7 , 1 1 , 1 3 , 1 7 , 1 9 , 2 3 ]
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23]
38
>>> objects[ - 3 ]
3
Slicing
Slicing is used to get sub list.
Example Description
list[start:end] Returns sub list from index start
(included) to end index
(excluded).
list[:end] Returns sub list from index
0(included) to end index
(excluded).
list[start:] Return sub list from index start
to till end.
list[-2:] Return list from 2 nd last to end.
>>> objects
[1, 3, 'Hello', 10.23]
>>> objects[ - 1 ]
10.23
>>> objects[ - 3 ]
3
>>> objects
[1, 3, 'Hello', 10.23]
>>>
>>> objects[:]
[1, 3, 'Hello', 10.23]
>>>
>>> objects[ 2 :]
['Hello', 10.23]
>>>
>>> objects[: 3 ]
[1, 3, 'Hello']
>>>
39
>>> objects[ - 2 :]
['Hello', 10.23]
Assignment to slices
If you want to replace sequence of elements in a list, you can use slice
notation.
40
Above statement replace elements at index 2, 3, 4 with 21, 22, 23
respectively.
numbers[:] = []
Above statement clear the list by replacing all the
elements with an empty list.
>>> numbers
[12, 14, 6, 8, 10, 1, 3, 5, 7, 9, 11, 13]
>>>
>>> numbers[ 2 : 5 ] = [ 2 1 , 2 2 , 2 3 ]
>>> numbers
[12, 14, 21, 22, 23, 1, 3, 5, 7, 9, 11, 13]
>>>
>>> numbers[:] = []
>>> numbers
[]
Nested lists
A list can be nested in other list. For example, in below example, numbers
contains 3 lists, first list represent odd numbers, second list represent even
numbers and third list represent prime numbers.
>>> numbers = [[ 1 , 3 , 5 , 7 ],[ 2 , 4 , 6 , 8 ],[ 2 , 3 , 5
, 7 , 1 1 ]]
>>> numbers
[[1, 3, 5, 7], [2, 4, 6, 8], [2, 3, 5, 7, 11]]
>>>
>>> numbers[ 0 ]
[1, 3, 5, 7]
>>>
>>> numbers[ 1 ]
[2, 4, 6, 8]
41
>>>
>>> numbers[ 2 ]
[2, 3, 5, 7, 11]
>>>
>>>
>>> len(numbers)
3
>>> len(numbers[ 0 ])
4
>>> len(numbers[ 1 ])
4
>>> len(numbers[ 2 ])
5
>>>
>>> numbers[ 0 ][ 1 ] = 9
>>> numbers[ 1 ][ 1 : 4 ] = [ 1 0 , 1 2 , 1 4 ]
>>> numbers
[[1, 9, 5, 7], [2, 10, 12, 14], [2, 3, 5, 7, 11]]
42
Python: tuples
A tuple is just like a list, consist of number of values separated by commas.
test.py
employee = ( 1 , "Hari Krihsna " , "Gurram " , 12345.67 8 )
print(employee)
print(employee[ 0 ])
print(employee[ 1 ])
print(employee[ 2 ])
print(employee[ 3 ])
$ python3 test.py
(1, 'Hari Krihsna', 'Gurram', 12345.678)
1
Hari Krihsna
Gurram
12345.678
test.py
employee = ( 1 , [])
print(employee)
employee[1 ]. append(2 )
employee[1 ]. append(4 )
employee[1 ]. append(6 )
43
print(employee)
$ python3 test.py
(1, [])
(1, [2, 4, 6])
test.py
employee = 1 , "Hari Krihsna " , "Gurram " , 12345.678
$ python3 test.py
1
Hari Krihsna
Gurram
12345.678
Concatenate tuples
‘+’ operator is used to concatenate tuples.
44
(1 , 'HI' , 2 , 45.65 , 'abcdef' , 54 , 67 )
Slicing
Just like lists, you can access tuples using slice notation.
Example Description
tuple[start:end] Returns tuple from index start
(included) to end index
(excluded).
tuple[:end] Returns tuple from index
0(included) to end index
(excluded).
tuple[start:] Return tuple from index start to
till end.
tuple[-2:] Return elements from 2 nd last
to end.
>>> tuple1
(1, 'HI', 2, 45.65)
>>> tuple1[ 0 :]
(1, 'HI', 2, 45.65)
>>> tuple1[:]
(1, 'HI', 2, 45.65)
>>> tuple1[: 3 ]
(1, 'HI', 2)
>>> tuple1[ 2 : 5 ]
(2, 45.65)
>>> tuple1
(1, 'HI', 2, 45.65)
>>>
45
>>> tuple1 * 3
(1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65)
>>>
Observe the output, an exception raised; this is because after deletion, tuple
does not exist any more.
46
Python: Sets
Set is an unordered collection of elements with no duplicates. We can
perform union, intersection, difference, and symmetric difference operations
on sets.
You can create set using {} (or) set() function. ‘set()’ creates empty set.
>>> evenNumbers={2, 4, 6, 8, 8, 4, 10} >>> evenNumbers {8, 10, 2, 4, 6}
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> 10 0 i n evenNumbers
False
>>>
>>> 2 i n evenNumbers
True
47
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> 1 0 no t i n evenNumbers
False
>>>
>>> 10 0 no t i n evenNumbers
True
isdisjoint(other)
Return true if two sets are disjoint, else false. Two
sets are said to be disjoint if they have no element
in common.
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> evenNumbers . isdisjoint({ 1 , 3 , 5 , 7 })
True
>>>
>>> evenNumbers . isdisjoint({ 1 , 3 , 5 , 7 , 8 })
False
issubset(other)
Return true, if this set is subset of other, else false.
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> evenNumbers . issubset({ 2 , 4 })
False
>>>
>>> evenNumbers . issubset({ 2 , 4 , 6 , 8 , 1 0 , 1 2 })
True
48
set < other
Return true, if the set is proper subset of other, that
is, set >= other and set != other.
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> evenNumbers < = { 2 , 4 , 6 , 8 , 1 0 }
True
>>> evenNumbers < = { 2 , 4 , 6 , 8 , 1 0 , 1 2 }
True
>>>
>>> evenNumbers < { 2 , 4 , 6 , 8 , 1 0 }
False
>>> evenNumbers < { 2 , 4 , 6 , 8 , 1 0 , 1 2 }
True
49
‘set - other - ...’
Return a new set with elements in the set that are
not in the others.
>>> evenNumbers
{8, 10, 2, 4, 6}
>>> powersOf2
{16, 8, 2, 4, 1}
>>> evenNumbers - powersOf2
{10, 6}
>>> powersOf2 - evenNumbers
{16, 1}
>>> evenNumbers
{8, 10, 2, 4, 6}
>>> powersOf2
{16, 8, 2, 4, 1}
>>> evenNumbers - powersOf2
{10, 6}
>>> powersOf2 - evenNumbers
{16, 1}
>>>
>>> evenNumbers ^ powersOf2
{1, 6, 10, 16}
>>> evenNumbers
{8, 10, 2, 4, 6}
50
>>> temp = evenNumbers . copy()
>>> temp
{8, 10, 2, 4, 6}
>>> evenNumbers
{8, 10, 2, 4, 6}
>>> oddNumbers
{9, 3, 5, 1, 7}
>>> powersOf2
{16, 8, 2, 4, 1}
>>>
>>> evenNumbers . update(oddNumbers, powersOf2)
>>> evenNumbers
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16}
51
{1}
Difference update
difference_update(other, ...)
set -= other | ...
Update the set, removing elements found in others.
>>> oddNumbers
{9, 3, 5, 1, 7}
>>> powersOf2
{16, 8, 2, 4, 1}
>>> oddNumbers . difference_update(powersOf2)
>>> oddNumbers
{9, 3, 5, 7}
>>> oddNumbers
{9, 3, 5, 7}
>>> powersOf2
{16, 8, 2, 4, 1}
>>> oddNumbers .
symmetric_difference_update(powersOf2)
>>> oddNumbers
{1, 2, 3, 4, 5, 7, 8, 9, 16}
>>> temp
{2, 3, 5, 7}
>>>
>>> temp . add( 1 1 )
52
>>> temp . add( 1 3 )
>>>
>>> temp
{2, 3, 5, 7, 11, 13}
>>> temp
{2, 3, 5, 7, 11, 13}
>>>
>>> temp . remove( 2 )
>>> temp
{3, 5, 7, 11, 13}
>>>
>>> temp . remove( 1 1 )
>>> temp
{3, 5, 7, 13}
>>> temp.remove(100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100
>>> temp
{5, 7, 13}
>>> temp . pop()
5
>>>
>>> temp . pop()
7
>>> temp . pop()
53
13
>>> temp . pop()
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
KeyErro r : 'pop from an empty set'
>>> powersOf2
{16, 8, 2, 4, 1}
>>>
>>> powersOf2 . clear()
>>> powersOf2
set()
54
Python modules
Module is a file, which contains definitions. We can define classes, modules,
variables etc., in module file and reuse them in other python scripts.
arithmetic.py
def sum (a, b):
return a+ b
def subtract (a, b):
return a- b
def mul (a,b):
return a* b
def div (a, b):
return a/ b
Open python interpreter, import the module using
‘import’ key word and call the functions defined in
module .
>>> impor t arithmetic
>>>
>>> arithmetic . sum( 1 0 , 2 0 )
30
>>> arithmetic . subtract( 1 0 , 2 0 )
-10
>>> arithmetic . mul( 1 0 , 2 0 )
200
>>> arithmetic . div( 1 0 , 2 0 )
0.5
55
>>> arithmetic.__name__
'arithmetic
arithmetic.py
def sum (a, b):
return a+ b
56
def subtract (a, b):
return a- b
def mul (a,b):
return a* b
def div (a, b):
return a/ b
main.py
impor t arithmetic
if __name__ == "__main__" :
import sys
a = int (sys. argv[1 ])
b = int (sys. argv[2 ])
print (sys. argv[0 ])
print ("a = " , a, "b = " , b)
print (arithmetic. sum(a,b))
print (arithmetic. subtract(a,b))
print (arithmetic. mul(a,b))
print (arithmetic. div(a,b))
$ python3 main.py 10 11
main.py
a = 10 b = 11
21
-1
110
0.9090909090909091
$ python3 main.py 8 13
main.py
a = 8 b = 13
57
21
-5
104
0.6153846153846154
58
Python: File handling
In this post and subsequent posts, I am going to explain how to open, read
and write to file.
Paramete Description
r
file Full path of the file to be opened.
mode Specifies the mode, in which the file
is opened. By default file opens in
read mode.
buffering 0: Switch off the buffer (only allowed
in binary mode)
1: Line buffering (only usable in text
mode)
59
device’s “block size” and falling
back on io.DEFAULT_BUFFER_SIZE.
b. “Interactive” text files use
line buffering.
encoding Type of encoding used to
encode/decode a file. This value
should be used in text mode. if
encoding is not specified the
encoding used is platform dependent.
errors Specifies how encoding and decoding
errors are to be handled. This cannot
be used in binary mode
newline controls how universal newlines
mode works. A manner of interpreting
text streams in which all of the
following are recognized as ending a
line: the Unix end-of-line convention
'\n', the Windows convention '\r\n',
and the old Macintosh convention '\r'.
closefd If closefd is False and a file descriptor
rather than a filename was given, the
underlying file descriptor will be kept
open when the file is closed. If a
filename is given closefd must be
True (the default) otherwise an error
will be raised
Following are different modes that you can use while opening a file.
Mod Description
e
'r' open for reading
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file
60
already exists
'a' open for writing, appending to the end of
the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and
writing)
For example, data.txt contains following data.
data.txt
First line
Second line
Third line
Fourth line
61
Python: classes and
objects
Class is a blue print to create objects.
Syntax
class ClassName :
< statement- 1 >
.
.
.
< statement- N>
‘class’ keyword is used to define a class. You can instantiate any number of
objects from a class.
Syntax
objName = new ClassName(arguments)
test.py
class Employee :
""" Employee class """
noOfEmployees= 0 # Class level variable
def __init__ (self , id , firstName, lastName):
self . id = id
self . firstName = firstName
self . lastName = lastName
Employee. noOfEmployees = Employee. noOfEmployees
+1
def displayEmployee (self ):
62
print (self . id, self . firstName, self . lastName)
emp1 = Employee( 1 , "Hari Krishna " , "Gurram " )
print( "Total Employees " , Employee . noOfEmployees)
emp2 = Employee( 2 , "PTR " , "Nayan " )
print( "Total Employees " , Employee . noOfEmployees)
emp3 = Employee( 3 , "Sankalp " , "Dubey " )
print( "Total Employees " , Employee . noOfEmployees)
emp1. displayEmployee()
emp2. displayEmployee()
emp3. displayEmployee()
$ python3 test.py
Total Employees 1
Total Employees 2
Total Employees 3
1 Hari Krishna Gurram
2 PTR Nayan
3 Sankalp Dubey
__init__(arguments)
__init__ is a special function called constructor used to initialize objects. In
Employee class, __init__ method is used to initialize id, firstName, lastName
to an object at the time of creation.
noOfEmployees=0
‘noOfEmployees’ is a class variable, shared by all the objects. Class variable
are accessed using Class name like ClassName.variableName,
‘Employee.noOfEmployees’ is used to access the class variable
noOfEmployees’.
Instance variables
Instance variables have values unique to an object. Usually these are defined
in __init__ method. Employee class has 3 instance variables id, firstName,
63
lastName.
The first parameter of any method in a class must be self. This parameter is
required even if the function does not use it. ‘self’ is used to refer current
object.
64
Python: Class Vs Instance
variables
Class variables are associated with class and available to all the instances
(objects) of the class, where as instance variables are unique to objects, used
to uniquely identify the object.
Employee.py
class Employee :
""" Blue print for all employees """
# Class level variables
noOfEmployees= 0
organization= "abcde corporation"
def __init__ (self , id =- 1 , firstName= "Nil" , lastName=
"Nil" ):
self . id = - 1
self . firstName = firstName
self . lastName = lastName
Employee. noOfEmployees+= 1
def displayEmployee (self ):
print (self . id, self . firstName, self . lastName)
emp1 = Employee(id = 1 , firstName= "Hari Krishna" ,
lastName= "Gurram" )
emp1. displayEmployee()
print( "Total Employees : " , Employee . noOfEmployees)
print( "Organization : " , Employee . organization)
emp2 = Employee(id = 3 , firstName= "PTR" )
emp2. displayEmployee()
65
print( "Total Employees : " , Employee . noOfEmployees)
print( "Organization : " , Employee . organization)
$ python3 Employee.py
-1 Hari Krishna Gurram
Total Employees : 1
Organization : abcde corporation
-1 PTR Nil
Total Employees : 2
Organization : abcde corporation
66
Python: Inheritance
Inheritance is the concept of re usability. Object of one class can get the
properties and methods of object of another class by using inheritance.
Syntax
class DerivedClassName (BaseClassName1,
BaseClassName2 ... BaseClassNameN):
< statement- 1 >
.
.
.
< statement- N>
inheritance.py
class Parent :
def printLastName (self ):
print ("Gurram" )
def printPermAddress (self ):
print ("State : Andhra Pradesh" )
print ("Country : India" )
class Child (Parent):
def printName (self ):
print ("Hari Krishna Gurram" )
child1 = Child()
child1. printName()
child1. printLastName()
child1. printPermAddress()
67
$ python3 inheritance.py
Hari Krishna Gurram
Gurram
State : Andhra Pradesh
Country : India
Observe above program, two classes parent and child are defined. Parent
class defines two methods printLastName, printPermAddress.
Child class defines one method printName. Child class inheriting the methods
printLastName, printPermAddress from parent class.
inheritance.py
class Parent :
def printLastName (self ):
print ("Gurram" )
def printPermAddress (self ):
print ("State : Andhra Pradesh" )
print ("Country : India" )
class Child (Parent):
def printName (self ):
print ("Hari Krishna" )
def printPermAddress (self ):
print ("City : Bangalore" )
print ("State : Karnataka" )
print ("Country : India" )
68
child1 = Child()
child1. printName()
child1. printLastName()
child1. printPermAddress()
$ python3 inheritance.py
Hari Krishna
Gurram
City : Bangalore
State : Karnataka
Country : India
69
Python: Exceptions
Exception is an event that disrupts the normal flow of execution. Even though
statements in your program are syntactically correct, they may cause an
error.
>>> 10 / 0
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
ZeroDivisionErro r : division by zero
>>>
>>> tempList = []
>>> tempList[ 2 0 ]
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
IndexErro r : list index out of range
Python: Handling
Exceptions
Python provide keywords try, except to handle exceptions.
test.py
while True :
try :
x = int (input ("Enter input " ))
print (x)
break ;
except ValueError :
70
print ("Please enter valid number" )
$ python3 test.py
Enter input an
Please enter valid number
Enter input ana
Please enter valid number
Enter input ptr
Please enter valid number
Enter input 10
10
How try and except block work?
The statements in try block executed first. If no exception occurs, the except
clauses are skipped and execution of the try statement is finished. If any
exception occurs during the execution of try block, the rest of the try clause
is skipped.
If an exception occurs which does not match the exception named in the
except clause, it is passed on to outer try statements; if no handler is found,
it is an unhandled exception and execution stops by throwing exception
message.
test.py
while True :
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
print (x/ y)
71
break ;
except ValueError :
print ("Please enter valid number" )
except ZeroDivisionError :
print ("y should be non zero" )
$ python3 test.py
Enter divisor 2
Enter dividend 0
y should be non zero
Enter divisor 4
Enter dividend 0
y should be non zero
Enter divisor 4
Enter dividend 2
2.0
test.py
while True :
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
print (x/ y)
break ;
except (ValueError , ZeroDivisionError ):
72
print ("Please enter valid number (or) y should be
greater than 0" )
$ python3 test.py
Enter divisor 2
Enter dividend 0
Please enter valid number (or) y should be greater than 0
Enter divisor aa
Please enter valid number (or) y should be greater than 0
Enter divisor 2
Enter dividend 4
0.5
Last except clause can omit exception name. It is used as global exception
handler.
test.py
while True :
try :
tempList= []
print (tempList[10 ])
break
except ValueError :
print ("Please enter valid number" )
except ZeroDivisionError :
print ("y should be non zero" )
except Exception as inst:
print ("Global handler" , inst)
break
$ python3 test.py
73
Global handler list index out of range
try…except…else clause
‘try…except’ statement can have optional else clause, it is followed by except
clause. If try block doesn’t throw any exception, else clause will be executed.
test.py
while True :
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
print (x/ y)
except ValueError :
print ("Please enter valid number" )
except ZeroDivisionError :
print ("y should be non zero" )
else :
print ("Program executed successfully" )
break
$ python3 test.py
Enter divisor 4
Enter dividend 2
2.0
Program executed successfully
Exception argument
Whenever an exception occurs, it is associated with a variable called
exception argument.
test.py
while True :
74
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
print (x/ y)
except ValueError as inst:
print (inst)
except ZeroDivisionError as inst:
print (inst)
else :
print ("Program executed successfully" )
break
$ python3 test.py
Enter divisor qwerty
invalid literal for int() with base 10: 'qwerty'
Enter divisor 4
Enter dividend 0
division by zero
Enter divisor 2
Enter dividend 4
0.5
Program executed successfully
The except clause can specify a variable after the exception name. The
variable is bound to an exception instance with the arguments stored in
instance.args.
test.py
while True :
try :
75
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
if y== 0 :
raise Exception (x, y)
print ("x/y = " ,x/ y)
break
except Exception as inst:
arg1, arg2 = inst. args
print ("arg1=" , arg1)
print ("arg2=" , arg2)
$ python3 test.py
Enter divisor 2
Enter dividend 0
arg1= 2
arg2= 0
Enter divisor 2
Enter dividend 4
x/y = 0.5
If an exception has arguments associated with it, those are printed as last
part of the exception message.
test.py
while True :
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
if y== 0 :
76
raise Exception (x, y)
print ("x/y = " ,x/ y)
break
except Exception as inst:
print (inst)
$ python3 test.py
Enter divisor 2
Enter dividend 0
(2, 0)
Enter divisor 2
Enter dividend 4
x/y = 0.5
test.py
def function1 ():
global data
data= "Hello World"
def function2 ():
print (data)
function1()
function2()
$ python3 test.py
77
Hello World
Observe ‘test.py’, even though data is declared in function1, it is accessed by
function2. It is because, data is declared in global scope.
78
Python: Get type of
variable
You can get the type of a variable using ‘type()’ function or __class__ property.
>>> data = [ 1 , 2 , 3 , 4 ]
>>> type(data)
<class 'list'>
>>> data . __class__
<class 'list'>
>>>
>>> data = { 1 : "hari " , 2 : "Krishna " }
>>> type(data)
<class 'dict'>
>>> data . __class__
<class 'dict'>
79
print ("data is of type dictionary" )
else :
print ("data is not dictionary type" )
80
PYTHON CODING
EXERCISES
81
Python Basic – Exercises
Get Python version
CODE
import sys
print("Python version")
print (sys.version)
print("Version info.")
print (sys.version_info)
OUTPUT
Python version
3.6.6 (default, Jun 28 2018, 04:42:43)
[GCC 5.4.0 20160609]
Version info.
sys.version_info(major=3, minor=6, micro=6,
releaselevel='final', serial=0)
82
Display current date and
time
PYTHON CODE
import datetime
now = datetime.datetime.now()
print ("Current date and time : ")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
OUTPUT
Current date and time :
2020-10-22 10:35:31
83
Print the calendar
PYTHON CODE
import calendar
y = int(input("Input the year : "))
m = int(input("Input the month : "))
print(calendar.month(y, m))
OUTPUT
Input the year : 2020
Input the month : 10
October 2020
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
84
Computes the value of
n+nn+nnn
PYTHON CODE
a = int(input("Input an integer : "))
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print (n1+n2+n3)
OUTPUT
Input an integer : 6
738
85
Calculate number of days
PROGRAM
from datetime import date
f_date = date(2014, 7, 2)
l_date = date(2015, 7, 11)
delta = l_date - f_date
print(delta.days)
OUTPUT
374
86
volume of a sphere in
Python
PROGRAM
pi = 3.1415926535897931
r= 6.0
V= 4.0/3.0*pi* r**3
print('The volume of the sphere is: ',V)
OUTPUT
The volume of the sphere is: 904.7786842338603
87
Compute the area of
Triangle
PROGRAM
b = int(input("Input the base : "))
h = int(input("Input the height : "))
area = b*h/2
88
Compute the GCD
PROGRAM
def gcd(x, y):
gcd = 1
if x % y == 0:
return y
print(gcd(12, 17))
print(gcd(4, 6))
OUTPUT
1
2
89
Calculate The LCM
PROGRAM
def lcm(x, y):
if x > y:
z=x
else:
z=y
while(True):
if((z % x == 0) and (z % y == 0)):
lcm = z
break
z += 1
return lcm
print(lcm(4, 6))
print(lcm(15, 17))
OUTPUT
12
255
90
Convert feet and inches
to centimeters
PROGRAM
print("Input your height: ")
h_ft = int(input("Feet: "))
h_inch = int(input("Inches: "))
h_inch += h_ft * 12
h_cm = round(h_inch * 2.54, 1)
91
Convert time – seconds
PYTHON CODE
days = int(input("Input days: ")) * 3600 * 24
hours = int(input("Input hours: ")) * 3600
minutes = int(input("Input minutes: ")) * 60
seconds = int(input("Input seconds: "))
92
Convert seconds to day
PROGRAM
time = float(input("Input time in seconds: "))
day = time // (24 * 3600)
time = time % (24 * 3600)
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
print("d:h:m:s-> %d:%d:%d:%d" % (day, hour, minutes,
seconds))
OUTPUT
Input time in seconds:
1234565
d:h:m:s-> 14:6:56:5
93
Calculate BMS
PROGRAM
height = float(input("Input your height in meters: "))
weight = float(input("Input your weight in kilogram: "))
print("Your body mass index is: ", round(weight / (height *
height), 2))
OUTPUT
Input your height in meters: 6.2
Input your weight in kilogram: 72
Your body mass index is: 1.87
94
Sort three integers
PROGRAM
x = int(input("Input first number: "))
y = int(input("Input second number: "))
z = int(input("Input third number: "))
a1 = min(x, y, z)
a3 = max(x, y, z)
a2 = (x + y + z) - a1 - a3
print("Numbers in sorted order: ", a1, a2, a3)
OUTPUT
Input first number:
2
Input second number:
4
Input third number:
5
Numbers in sorted order: 2 4 5
95
Get system time
PROGRAM
import time
print()
print(time.ctime())
print()
OUTPUT
Thu Oct 22 14:59:27 2020
96
Check a number
PYTHON CODE
num = float(input("Input a number: "))
if num > 0:
print("It is positive number")
elif num == 0:
print("It is Zero")
else:
print("It is a negative number")
OUTPUT
Input a number: 200
It is positive number
97
Python code to Remove
first item
PROGRAM
color = ["Red", "Black", "Green", "White", "Orange"]
print("\nOriginal Color: ",color)
del color[0]
print("After removing the first color: ",color)
print()
OUTPUT
Original Color: ['Red', 'Black', 'Green', 'White', 'Orange']
After removing the first color: ['Black', 'Green', 'White',
'Orange']
98
Filter positive numbers
PYTHON CODE
nums = [34, 1, 0, -23]
print("Original numbers in the list: ",nums)
new_nums = list(filter(lambda x: x >0, nums))
print("Positive numbers in the list: ",new_nums)
OUTPUT
Original numbers in the list: [34, 1, 0,
-23]
Positive numbers in the list: [34, 1]
99
Count the number 4
in a given list
SAMPLE PROGRAM
def list_count_4(nums):
count = 0
for num in nums:
if num == 4:
count = count + 1
return count
print(list_count_4([1, 4, 6, 7, 4]))
print(list_count_4([1, 4, 6, 4, 7, 4]))
OUTPUT
2
100
Find a number even or
odd
SAMPLE PROGRAM
num = int(input("Enter a number: "))
mod = num % 2
if mod > 0:
print("This is an odd number.")
else:
print("This is an even number.")
OUTPUT
Enter a number:
5
101
Get n copies of a given
string
PROGRAM
def larger_string(str, n):
result = ""
for i in range(n):
result = result + str
return result
print(larger_string('abc', 2))
print(larger_string('.py', 3))
OUTPUT
abcabc
.py.py.py
102
Print out a list which are
not present in other list
DATA
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
Expected Output :
{'Black', 'White'}
SAMPLE PROGRAM
color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
print(color_list_1.difference(color_list_2))
OUTPUT
{'White', 'Black'}
103
Display details name,
age, address in three
different lines
SAMPLE PROGRAM
def personal_details():
name, age = "JJ Tam", 28
address = "Bangalore, Karnataka, India"
print("Name: {}\nAge: {}\nAddress: {}".format(name,
age, address))
personal_details()
OUTPUT
Name: JJ Tam
Age: 28
Address: Bangalore, Karnataka, India
104
Program to solve
(x + y) * (x + y)
DATA
program to solve (x + y) * (x + y).
Test Data : x = 4, y = 3
Expected Output : (4 + 3) ^ 2) = 49
PROGRAM
x, y = 4, 3
result = x * x + 2 * x * y + y * y
print("({} + {}) ^ 2) = {}".format(x, y, result))
OUTPUT
(4 + 3) ^ 2) = 49
105
Future value of amount
Of the given rate of interest,
and a number of years
DATA
Test Data : amt = 10000, int = 3.5, years = 7
Expected Output : 12722.79
PROGRAM
amt = 10000
int = 3.5
years = 7
106
Check whether a file
exists
PROGRAM
import os.path
open('abc.txt', 'w')
print(os.path.isfile('abc.txt'))
OUTPUT
True
107
Convert the distance
Feet to inches, yards, and
miles
SAMPLE PROGRAM
d_ft = int(input("Input distance in feet: "))
d_inches = d_ft * 12
d_yards = d_ft / 3.0
d_miles = d_ft / 5280.0
108
Sum all the items
in a list
Python Code
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
OUTPUT
-5
109
Multiplies all the items
in a list
Python Code
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
OUTPUT
-16
110
Get the largest number
from a list
Python Code
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
OUTPUT
2
111
Get the smallest number
from a list
PYTHON CODE
def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))
OUTPUT
-8
112
Remove duplicates
from a list
PROGRAM
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Output:
{40, 10, 80, 50, 20, 60, 30}
113
Clone or copy a list
PYTHON CODE
original_list = [10, 22, 44, 23, 4]
new_list = list(original_list)
print(original_list)
print(new_list)
OUTPUT
[10, 22, 44, 23,
4]
114
Difference between the
two lists
PYTHON CODE
list1 = [1, 3, 5, 7, 9]
list2=[1, 2, 4, 6, 7, 8]
diff_list1_list2 = list(set(list1) - set(list2))
diff_list2_list1 = list(set(list2) - set(list1))
total_diff = diff_list1_list2 + diff_list2_list1
print(total_diff)
OUTPUT
[9, 3, 5, 8, 2, 4, 6]
115
Generate all
permutations
of a list
PYTHON CODE
import itertools
print(list(itertools.permutations([1,2,3])))
OUTPUT
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
116
Find the second smallest
number in a list
PYTHON PROGRAM
def second_smallest(numbers):
if (len(numbers)<2):
return
if ((len(numbers)==2) and (numbers[0] ==
numbers[1]) ):
return
dup_items = set()
uniq_items = []
for x in numbers:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
uniq_items.sort()
return uniq_items[1]
117
0
None
None
118
Get unique values
from a list
Python Code
my_list = [10, 20, 30, 40, 20, 50, 60, 40]
print("Original List : ",my_list)
my_set = set(my_list)
my_new_list = list(my_set)
print("List of unique numbers : ",my_new_list)
OUTPUT
Original List : [10, 20, 30, 40, 20, 50, 60,
40]
List of unique numbers : [40, 10, 50, 20, 60, 30]
119
Get the frequency of the
elements
Python Code
import collections
my_list = [10,10,10,10,20,20,20,20,40,40,50,50,30]
print("Original List : ",my_list)
ctr = collections.Counter(my_list)
print("Frequency of the elements in the List : ",ctr)
OUTPUT
Original List : [10, 10, 10, 10, 20, 20, 20, 20, 40, 40, 50,
50, 30]
Frequency of the elements in the List : Counter({10: 4,
20: 4, 40: 2, 50: 2, 30: 1})
120
Generate all sublists
of a list in Python
Python Code
from itertools import combinations
def sub_lists(my_list):
subs = []
for i in range(0, len(my_list)+1):
temp = [list(x) for x in combinations(my_list, i)]
if len(temp)>0:
subs.extend(temp)
return subs
OUTPUT
Original list:
121
[10, 20, 30, 40]
S
[[], [10], [20], [30], [40], [10, 20], [10, 30], [10, 40], [20,
30], [20, 40], [30, 40], [10, 20, 30], [10, 20, 40], [10, 30,
40], [20, 30, 40], [10, 20, 30, 40]]
Sublists of the said list:
[[], [10], [20], [30], [40], [10, 20], [10, 30], [10, 40], [20,
30], [20, 40], [30, 40], [10, 20, 30], [10, 20, 40], [10, 30,
40], [20, 30, 40], [10, 20, 30, 40]]
Original list:
['X', 'Y', 'Z']
Sublists of the said list:
[[], ['X'], ['Y'], ['Z'], ['X', 'Y'], ['X', 'Z'], ['Y', 'Z'], ['X', 'Y', 'Z']]
122
Find common items
from two lists
Python Code
color1 = "Red", "Green", "Orange", "White"
color2 = "Black", "Green", "White", "Pink"
print(set(color1) & set(color2))
OUTPUT
'Green', 'White'}
123
Create a list
with infinite elements
Python Code
import itertools
c = itertools.count()
print(next(c))
print(next(c))
print(next(c))
print(next(c))
print(next(c))
OUTPUT
0
124
Remove consecutive
duplicates
of a given list
Python Code
from itertools import groupby
def compress(l_nums):
return [key for key, group in groupby(l_nums)]
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print("Original list:")
print(n_list)
print("\nAfter removing consecutive duplicates:")
print(compress(n_list))
OUTPUT
Original list:
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
125
Flatten a nested
list structure
Python Code
def flatten_list(n_list):
result_list = []
if not n_list: return result_list
stack = [list(n_list)]
while stack:
c_num = stack.pop()
next = c_num.pop()
if c_num: stack.append(c_num)
if isinstance(next, list):
if next: stack.append(list(next))
else: result_list.append(next)
result_list.reverse()
return result_list
n_list = [0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100,
110, 120]]
print("Original list:")
print(n_list)
print("\nFlatten list:")
print(flatten_list(n_list))
OUTPUT
Original list:
[0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
126
Flatten list:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
127