Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Learn Python Quickly

Uploaded by

Y W Leung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Learn Python Quickly

Uploaded by

Y W Leung
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

LEARN PYTHON

QUICKLY
AND
PYTHON CODING
EXERCISES

CODING FOR BEGINNERS


WITH HANDS ON PROJECTS
BY
J J TAM

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

CODING FOR BEGINNERS


WITH HANDS ON PROJECTS
BY
J J TAM

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?

Following are some of the reasons that forced me to learn


python…(First and best reason is I am fed up in working
with same language for 5 years……….:))
a. Python is open source and is available on Windows,
Mac OS X, and Unix operating systems. You can download
and work with python for free.
b. Python is fun to experiment and easy to learn. Python
provides interpreter that can be used interactively, which
makes it easy to experiment with features of the
language.
c. You can extend the python interpreter with new
functions and data types implemented in C or C++
d. Python improves developer productivity many times
as compared to C, C++ and Java.
e. No need to compile python program, it runs
immediately after development.
f. We can easily port python project from one platform
to another (Of course Java also provides this feature)
g. Rich in built library. Many third party open source
libraries are available for logging, web development
(Django — the popular open source web application
framework written in Python), networking, database
access etc.

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/

Step 2: Click the pkg file.

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.

Once installation is successful, you will get following screen.

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()

Use ‘quit()’ to exit from python prompt.

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

What happens when you instruct python to run your script?


Python first compiles your source code to byte code and sends it to python
virtual machine (PVM). Byte code is the platform independent representation
of your source code. PVM reads the byte code one by one and execute them.

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.
>>>

How to exit from python interpreter


On Windows, a Ctrl-Z gets you out of this session;
on Unix, try Ctrl-D instead. Another way is simply
call the quit() function to quit from python.
$ 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.
>>> quit()
$
You can type any statement (or) expressions in
python interpreter, interpreter execute those
statements and gives you the result.
>>> 10+20
30
>>> 20*20

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

Following are the arithmetic operators supported by python.

Operat Description Example


or
+ Addition 2+3
- Subtraction 2-3
* Multiplication 2*3
/ Division always 2/3 returns
returns a float 0.666666666666666
value. To get only 6
integer result use
//.
// Floor division 2//3 returns 0
discards the
fractional part
% Returns the 2%3
remainder of the
division.
** Power 2**3 returns 2 power
3 =8

>>> 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.

Operato Description Example


r
== Equal to a==b returns
true if a is equal
to b, else false
!= Not equal to a!=b returns true
if a is not equal to
b, else false.
> Greater than a>b returns true,
if a is > b, else
false.
>= Greater than or a>=b returns
equal to true, if a is >= b,
else false.
< Less than a<b returns true,
if a is < b, else
false.
<= Less than or equal a<=b returns
to true, if a is <= b,

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.

>>> name1 = "Hari Krishna"


>>> name2 = name1
>>> name3 = "Hari Krishna"
>>> name4 = "abc"
>>>
>>> name1 i s name2
True
>>> name1 i s name3
False
>>> name1 i s name4
False
>>> name1 i s no t name3
True

Python: Short circuit


operators
Boolean operators and, or are called short circuit operators, it Is because
evaluation of expression stops, whenever the outcome determined.

Why Boolean and is called short circuit operator?


Since if the first statement in the expression evaluates to false, then python
won't evaluates the entire expression. So boolean and is called short circuit
and.

Why Boolean OR is called short circuit operator?


Since if the first statement evaluates to true, then Python won't evaluates the
entire expression.

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'

Special characters are escaped with backslash.


>>> message = 'He don \' t know about this'
>>> message
"He don't know about this"

‘print’ method treat characters preceded by \ (backslash) as special


characters.

>>> prin t ( 'firstline \n secondline ' )


firstline
secondline

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

>>> prin t ( r'firstline\nsecondline ' )


firstline\nsecondline

23
Concatenate strings
'+' operator is used to concatenate strings.

>>> hello = "Hello,"


>>> message = "How are you"
>>> info = hello + message
>>> info
'Hello,How are you'

Two or more string literals next to each other are automatically concatenated.

>>> 'Hello ' "How " 'are ' 'you'


'HelloHowareyou'

Repeat strings
By using ‘*’, we can repeat the strings.

>>> 'hi' * 2
'hihi'
>>> 'hi' * 2 + 'hello' * 3
'hihihellohellohello'

Access specific character from strings


You can access, specific character of string using index position.

>>> name = "Hello World"


>>> name[ 0 ]
'H'
>>> name[ 6 ]
'W'

st nd
Index 0 represents 1 character, 1 represents 2 character etc.,

You can also use negative numbers for indexing.

-1 represents last character; -2 represents second-last 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.

>>> message = "Hello World"


>>>
>>> message[ 0 : 5 ]
'Hello'
>>> message[ 5 :]
' World'
>>> message[:]
'Hello World'
>>> message[ - 2 :]
'ld'
>>> message[ - 5 : - 2 ]
'Wor'

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

( "Even numbers are


prin t " )
while (a < 10 ) :
print (a, end= ' ' )
a += 2
else :
print (" \n Exit from loop" )
prin t ( "Done " )
$ python3 test.py
Even numbers are
2468
Exit from loop
Done

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]

‘else’ clause is optional, it is executes, once the loop terminates.

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

Variables created before function definition may be read inside of


the function only if the function does not change the value.
test.py
# Create the x variable and set to 44

34
x = 44

# Define a simple function that prints x


def f ():
x += 1
print (x)
# Call the function
f()

Run above program, you will get following error.


$ python3 test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
f()
File "test.py", line 7, in f
x += 1
UnboundLocalError: local variable 'x' referenced before assignment

Remove ‘x+=1’ statement and re run the above


program, value of x is printed to console.

35
Python: functions: return
statement
‘return’ statement is used to return a value from function to the caller.

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

‘return’ without an expression argument returns None.

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]

‘primes’ is a list that contain prime numbers.


>>> students = [ "Hari " , "Krishna " , "Kiran " , "Ravi " ]
>>> students
['Hari', 'Krishna', 'Kiran', 'Ravi']

‘students’ is a list that contain all student names.

List can contain any type of data.


>>> objects = [ 1 , 3 , "Hello " , 10.2 3 ]
>>> objects
[1, 3, 'Hello', 10.23]

You can access elements of list by using index.


>>> objects
[1, 3, 'Hello', 10.23]
>>> objects[ 0 ]
1
>>> objects[ 2 ]
'Hello'

objects[0] return the first element of list objects.


objects[1] return the second element of list objects.

-ve indexes also used to access elements of a list.


>>> objects
[1, 3, 'Hello', 10.23]
>>> objects[ - 1 ]
10.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]

Concatenate two lists


'+' Operator is used to concatenate two lists.
>>> even = [ 2 , 4 , 6 , 8 , 1 0 ]
>>> odd = [ 1 , 3 , 5 , 7 , 9 ]
>>> numbers = even + odd
>>> numbers
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]

Lists are mutable; you can change the values of


list.
>>> numbers
[2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
>>> numbers[ 0 ] = 12
>>> numbers[ 1 ] = 14
>>> numbers
[12, 14, 6, 8, 10, 1, 3, 5, 7, 9]

Add elements to end of list


List provides ‘append’ method to add new elements
to the end of a list.
>>> numbers
[12, 14, 6, 8, 10, 1, 3, 5, 7, 9]
>>>
>>> numbers . append( 1 1 )
>>> numbers . append( 1 3 )
>>>
>>> numbers
[12, 14, 6, 8, 10, 1, 3, 5, 7, 9, 11, 13]

Assignment to slices
If you want to replace sequence of elements in a list, you can use slice
notation.

numbers[2:5] = [21, 22, 23]

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
[]

Get length of the list


By using ‘len’ function, you can get the length of the list.
>>> vowels = [ 'a ' , 'e ' , 'i ' , 'o ' , 'u ' ]
>>> len(vowels)
5

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.

Differences between tuple and list


a . List is mutable, where as tuple is immutable
b . Tuple can contain heterogeneous data, where as list usually contains
homogeneous data.

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

As you observe above example, elements in tuple are enclosed in


parenthesis. Eventhough tuples are immutable, you can create tuples which
contain mutable objects, such as lists.

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])

Packing and unpacking


You can define tuples, without using parenthesis.
For example,
employee=1, "Hari Krihsna", "Gurram", 12345.678

Above one is the example of tuple packing.

id, firstName, lastName, salary = employee


Above one is an example of tuple unpacking. Sequence unpacking requires
that there are as many variables on the left side of the equals sign as there
are elements in the sequence.

test.py
employee = 1 , "Hari Krihsna " , "Gurram " , 12345.678

id, firstName, lastName, salary = employee


print(id)
print(firstName)
print(lastName)
print(salary)

$ python3 test.py
1
Hari Krihsna
Gurram
12345.678

Concatenate tuples
‘+’ operator is used to concatenate tuples.

>> > tuple1 = ( 1 , "HI " , 2 , 45.6 5 )


>> > tuple2 = ( "abcdef " , 5 4 , 6 7 )
>> > tuple3 = tuple1 + tuple2
>>> tuple3

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)

‘*’: Repeat tuple elements


‘*’ is the repetition operator, used to repeat the elements of tuple.

>>> tuple1
(1, 'HI', 2, 45.65)
>>>

45
>>> tuple1 * 3
(1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65, 1, 'HI', 2, 45.65)
>>>

Remove tuple elements


As I said, tuples are immutable, so it is not possible to remove elements from
tuple. But you can remove the entire tuple using del statement.
>>> tuple1 = ( 1 , "HI " , 2 , 45.6 5 )
>>>
>>> de ltuple1
>>> tuple1
Traceback (most recent call last):
File "<stdin>" , line 1 , in <module>
NameErro r : name 'tuple1' is not defined

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.

How to create set

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}

Observe above snippet, evenNumbers is a set that contains even numbers.


Observe the output, set doesn’t contain duplicate elements.

Following operations are supported by set.

len(s) : cardinality of set


Returns cardinality(Number of distinct elements) of
the set.
>>> evenNumbers = { 2 , 4 , 6 , 8 , 8 , 4 , 1 0 }
>>> len(evenNumbers)
5

x in s : Check whether element is in set or not


‘in’ operator is used to check whether element is in set or not, return true if
the element is set, else false.

>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> 10 0 i n evenNumbers
False
>>>
>>> 2 i n evenNumbers
True

x not in s : Check whether element is in set or not


‘not in’ operator is opposite of ‘in’ operator, return true if the element is not
in set, else false.

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

set <= other


Return true if every element in the set is in other.

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

Union of two sets


union(other, ...)
‘set | other | ...’
>>> evenNumbers = { 2 , 4 , 6 , 8 , 1 0 }
>>> oddNumbers = { 1 , 3 , 5 , 7 , 9 }
>>> result = evenNumbers | oddNumbers
>>> result
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

Intersection of two sets


intersection(other, ...)
‘set & other & ...’
>>> evenNumbers = { 2 , 4 , 6 , 8 , 1 0 }
>>> powersOf2 = { 1 , 2 , 4 , 8 , 1 6 }
>>> result = evenNumbers & powersOf2
>>> result
{8, 2, 4}

Difference between two sets


difference(other, ...)

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}

Symmetric difference between two sets


symmetric_difference(other)
set ^ other
If A and B are two sets, then Simmetric difference between A and B is A^B =
(A-B) union (B-A)

>>> 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}

Copy elements of set


‘copy’ function return a new set with a shallow copy of s.

>>> evenNumbers
{8, 10, 2, 4, 6}

50
>>> temp = evenNumbers . copy()
>>> temp
{8, 10, 2, 4, 6}

Update the set


update(other, ...)
set |= other | ...

Update the set by adding elements from other sets.

>>> 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}

Intersection of all sets


intersection_update(other, ...)
set &= other & ...

Update the set, keeping only elements found in it


and all others.
>>> numbers
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 16}
>>> oddNumbers
{9, 3, 5, 1, 7}
>>> powersOf2
{16, 8, 2, 4, 1}
>>> numbers . intersection_update(oddNumbers,
powersOf2)
>>> numbers

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}

Symmetric difference update


symmetric_difference_update
set ^= other
Update the set, keeping only elements found in either set, but not in both.

>>> 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}

Add element to the set


‘add’ method is used to add element to set.

>>> temp
{2, 3, 5, 7}
>>>
>>> temp . add( 1 1 )

52
>>> temp . add( 1 3 )
>>>
>>> temp
{2, 3, 5, 7, 11, 13}

Remove an element from set


‘remove’ method is used to remove element from set.

>>> 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}

Throws KeyError, if element is not in the set.

>>> temp.remove(100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 100

Remove arbitrary element from set


‘pop()’ is used to remove and return an arbitrary element from the set.
Throws KeyError, if the set is empty.

>>> 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'

Remove all elements from set


‘clear’ method is used to remove all elements from 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.

For example, create a file ‘arithmetic.py’ and copy following code.

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

How to get the module name


By using the property ‘__name__’, you can get the module name.

55
>>> arithmetic.__name__
'arithmetic

Use functions of module as local functions

>>> impor t arithmetic


>>> sum = arithmetic . sum
>>> sub = arithmetic . subtract
>>> mul = arithmetic . mul
>>> div = arithmetic . div
>>>
>>> sum( 1 0 , 2 0 )
30
>>> mul( 1 0 , 2 0 )
200
>>> sub( 1 0 , 2 0 )
-10

Python command line


arguments
Python scripts accept any number of arguments from command line. This
option facilitates us to configure Application at the time of running.

How to pass command line arguments


pyhon scriptname arg1 arg2 …argN

By using ‘sys’ module we can access command line arguments.

sys.argv[0] contains file name


sys.argv[1] contains first command line argument, sys.argv[2] contains
second command line argument etc.,

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.

How to open file


To read data from a file (or) to write data to a file, we need a reference object
that points to file. ‘open’ method is used to get a file object.

open(file, mode='r', buffering=-1, encoding=None, errors=None,


newline=None, closefd=True, opener=None)
'open' function opens file in specific mode and return corresponding file
object. Throws OSError, if it is unable to open a 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)

>1: Specify the size of buffer in


bytes.
If you don't specify any value, by
default buffering works like below.
a. Binary files are buffered in
fixed-size chunks; the size of the
buffer is chosen using a heuristic
trying to determine the underlying

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

>>> f = open( "/Users/harikrishna_gurram/data.txt " )


>>>
>>> f . read()
'First line\nSecond line\nThird line\nFourth line\n'

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

As you observe Employee.py noOfEmployees, organization are class


variables, are available to all the instances. Class variables are accessed
using ClassName followed by dot followed by variable name.

Employee.noOfEmployees: is used to access class variable


noOfEmployees.
Employee.organization: is used to access class variable organization.

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.

Overriding the methods of Parent class


You can override the properties, methods of parent class in child class. For
example, following application overrides ‘printPermAddress’ method of 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

Observer above snippet, ‘10/0’ causes ZeroDivisionError. When program tries


th
to access 20 element of tempList it causes IndexError.

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.

‘try’ block followed by number of except clauses, if exception thrown in try


cause matches to any exception followed by except clause, then particular
except clause is executed.

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.

Try block can be followed by multiple except clauses

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

Handling multiple exceptions in single except clause


An except clause can catch more than one exception. For example ‘except
(ValueError, ZeroDivisionError)’ can handle both ValueError and
ZeroDivisionError.

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

Python global keyword


‘global’ keyword is used to create/change a global variables (You can declare
functions, classes etc. also) from local context.

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'>

Checking the type using if statement


data = { 1 : "hari " , 2 : "Krishna " }
#Approach 1
if (data. __class__. __name__ == 'dict' ):
print ("data is of type dictionary" )
else :
print ("data is not dictionary type" )
#Approach 2
if (type (data). __name__ == 'dict' ):
print ("data is of type dictionary" )
else :
print ("data is not dictionary type" )
#Approach 3
if type (data)== type (dict ()):

79
print ("data is of type dictionary" )
else :
print ("data is not dictionary type" )

Run above program, you will get following output.


data is of type dictionary
data is of type dictionary
data is of type dictionary

Check whether an object is instance of class or not


‘isinstance(object, classinfo)’ method is used to check whether an object is
instance of given class or not. Return true if the object argument is an
instance of the classinfo argument, or of a subclass thereof, else false.
data = { 1 : "hari " , 2 : "Krishna " }
class Employee :
def __init__ (self , id , firstName, lastName):
self . id = id
self . firstName = firstName
self . lastName = lastName
emp = Employee( 1 , "Hari " , "Krishna " )
print(isinstance(emp, Employee))
print(isinstance(emp, dict))
print(isinstance(data, dict))

Run above program, you will get following output.


True
False
True

80
PYTHON CODING
EXERCISES

CODING FOR BEGINNERS


JJ TAM

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

print("area = ", area)


OUTPUT
Input the base : 20
Input the height : 40
area = 400.0

88
Compute the GCD
PROGRAM
def gcd(x, y):
gcd = 1

if x % y == 0:
return y

for k in range(int(y / 2), 0, -1):


if x % k == 0 and y % k == 0:
gcd = k
break
return gcd

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)

print("Your height is : %d cm." % h_cm)


OUTPUT
Input your height:
Feet: 5
Inches: 3
Your height is : 160 cm.

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: "))

time = days + hours + minutes + seconds

print("The amounts of seconds", time)


Output:
Input days: 4
Input hours: 5
Input minutes: 20
Input seconds: 10
The amounts of seconds 364810

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

This is an odd number.

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

future_value = amt*((1+(0.01*int)) ** years)


print(round(future_value,2))
OUTPUT
12722.79

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

print("The distance in inches is %i inches." % d_inches)


print("The distance in yards is %.2f yards." % d_yards)
print("The distance in miles is %.2f miles." % d_miles)
OUTPUT
Input distance in feet:
100
The distance in inches is 1200
inches.
The distance in yards is 33.33
yards.
The distance in miles is 0.02 miles.

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]

[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]

print(second_smallest([1, 2, -8, -2, 0, -2]))


print(second_smallest([1, 1, 0, 0, 2, -2, -2]))
print(second_smallest([1, 1, 1, 0, 0, 0, 2, -2, -2]))
print(second_smallest([2,2]))
print(second_smallest([2]))
OUTPUT
-2
0

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

l1 = [10, 20, 30, 40]


l2 = ['X', 'Y', 'Z']
print("Original list:")
print(l1)
print("S")
print(sub_lists(l1))
print("Sublists of the said list:")
print(sub_lists(l1))
print("\nOriginal list:")
print(l2)
print("Sublists of the said list:")
print(sub_lists(l2))

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]

After removing consecutive duplicates:


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 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

You might also like