Learn Python Quickly and Python Coding Exercises Coding For Beginners B08RDY478F
Learn Python Quickly and Python Coding Exercises Coding For Beginners B08RDY478F
QUICKLY
AND
PYTHON CODING EXERCISES
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.
h. Python has very great community, whatever the problem you faced in
python, you will get quick help.
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.
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.
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’.
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.
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.
>>>
Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators in python
>>> 4 + 2
6
>>> 4 - 2
2
>>> 4 / 2
2.0
>>> 4 * 2
8
>>> 4 // 2
2
>>> 4 ** 2
16
>>> a = 10
>>> b = 12
>>> a == b
False
>>>a != b
True
>>> a > b
False
>>> a >= b
False
>>>a < b
True
>>>a <= b
True
>>>
Operator Description
= 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
%= 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 = 10 , 'hello ' , 12.345
>>> a
10
>>> b
'hello'
>>> c
12.345
Operator Description
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
>>>
>>>aor b
True
>>>
>>> no t a
True
>>>
>>> no t (a an d b)
True
>>>
>>> no t ( a o r b)
False
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
>>> a |3
3
>>>
>>> ~ a
-3
Operator Description
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
Operator Description
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.
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
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'
>>> name
'Hello World'
>>> 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.
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 :
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
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
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
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
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.
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
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
x= 44
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
Hello
None
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]
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']
>>>
>>> objects[ -2 :]
['Hello', 10.23]
Assignment to slices
If you want to replace sequence of elements in a list, you can use slice notation.
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]
>>>
>>> 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]]
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
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 )
print(employee)
$ python3 test.py
(1, [])
(1, [2, 4, 6])
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.
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)
>>>
>>> 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.
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}
Observe above snippet, evenNumbers is a set that contains even numbers. Observe the output, set
doesn’t contain duplicate elements.
>>> evenNumbers
{8, 10, 2, 4, 6}
>>>
>>> 10 0 i n evenNumbers
False
>>>
>>> 2 i n evenNumbers
True
>>> 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
>>> 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}
>>> temp = evenNumbers . copy()
>>> temp
{8, 10, 2, 4, 6}
Update the set
update(other, ...)
set |= other | ...
>>> 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}
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
{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( 11 )
>>> temp . add( 13 )
>>>
>>> temp
{2, 3, 5, 7, 11, 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()
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()
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
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
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
21
-5
104
0.6153846153846154
Python: File handling
In this post and subsequent posts, I am going to explain how to open, read and write to file.
Parameter Description
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
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.
Mode Description
'r' open for reading
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file 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'
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 ):
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, 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.
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()
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.
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()
$ 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" )
child1 = Child()
child1. printName()
child1. printLastName()
child1. printPermAddress()
$ python3 inheritance.py
Hari Krishna
Gurram
City : Bangalore
State : Karnataka
Country : India
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 to access 20 th element
of tempList it causes IndexError.
test.py
while True :
try :
x = int (input ("Enter input " ))
print (x)
break ;
except ValueError :
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.
test.py
while True :
try :
x = int (input ("Enter divisor " ))
y = int (input ("Enter dividend " ))
print (x/ y)
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 ):
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
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 :
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 :
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 :
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
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.
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'>
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)
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
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
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
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
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
Compute the area of Triangle
PROGRAM
b = int(input("Input the base : "))
h = int(input("Input the height : "))
area = b*h/2
if x % y == 0:
return y
print(gcd(12, 17))
print(gcd(4, 6))
OUTPUT
1
2
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
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)
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
Get system time
PROGRAM
import time
print()
print(time.ctime())
print()
OUTPUT
Thu Oct 22 14:59:27 2020
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
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']
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]
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
3
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.
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
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'}
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
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
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
OUTPUT
-5
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
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
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
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}
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]
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]
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)]
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]
OUTPUT
Original List : [10, 20, 30, 40, 20, 50, 60,
40]
List of unique numbers : [40, 10, 50, 20, 60, 30]
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})
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
Original list:
['X', 'Y', 'Z']
Sublists of the said list:
[[], ['X'], ['Y'], ['Z'], ['X', 'Y'], ['X', 'Z'], ['Y', 'Z'], ['X', 'Y', 'Z']]
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'}
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
1
2
3
4
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]
OUTPUT
Original list:
[0, 10, [20, 30], 40, 50, [60, 70, 80], [90, 100, 110, 120]]
Flatten list:
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]