Sei sulla pagina 1di 131

PYTHON PROGRAMMING

Introduction
Python is a very powerful high-level,general-purpose, object-oriented
programming language created by Guido van Rossum in 1989.

Python is very popular for developers and professionals because, it


has a rich set of supporting libraries, and addon modules. It is a cross-
platform(platform-independent) language and runs on all major operating
systems including Windows, Linux, and Macintosh. Python comes with a
powerful and easy to-use graphical user interface (GUI) toolkit that makes
the task of developing GUI applications.

History of Python
The Python programming language was conceived in the late
1980s, and its implementation was started in December 1989 by
Guido van Rossum at CWI(Centrum Wiskunde & Informatica) in the
Netherlands as a successor of ABC programming language. Python
was published in 1991.

Python Versions and Release Dates


Release dates for the major versions
· Python 1.0 - January 1994
· Python 1.5 - December 31, 1997
· Python 2.0 - October 16, 2000
· Python 2.5 - September 19, 2006
· Python 3.0 - December 3, 2008
· Python 3.4 - March 16, 2014
· Python 3.5 - September 13, 2015
· Python 3.6 - December 23, 2016
· Python 3.6.5 March28 , 2018
· Python 3.7.0 June 27 , 2018
· Python 3.7.1 October 20 , 2018
· Python 3.7.2 Dec. 24 - 2018
Note : Latest version of Python Python 3.7.3 March 25, 2019
Features of Python
· Python is easy to learn.
· It has easier to read syntax.
· Python is free.
· It comes with a large number of libraries.
· Python can be integrated with other languages,
like C, C++, and Java.
· Python is a good choice for web development.
· Efficient memory management.
· Python supports exception handling.

Installing Python
To install Python, you will need to download its most recent
distribution from the following URL: www.python.org. Let’s have
a look at the steps for installing Python on Microsoft Windows.

Installing Python on Microsoft Windows


For Microsoft Windows, download the latest Python installer
program from its site, and then double-click on it to begin the
installation wizard.
The first dialog box of the installation wizard, shown in Figure
Python installation wizard.

In the next dialog, you will be asked for the destination folder where
you want to install Python files. The wizard also displays a folder name by
default that represents the Python version being installed. Select the Next
button to continue. The next dialog is to specify the Python features (i.e.,
the components) that you want to install, as shown in Figure
Selecting Python components to install.

The installer program will copy the Python files to the selected folder,
and you will be asked to select the Finish button to exit the installation
wizard.

Interacting with Python


There are two ways to work with Python :
· Using Command Line Mode
· Using IDLE

Command Line Mode


On selecting the Python Command Line, you see the Python Command
Line window displaying the Python prompt (>>>), as shown in Figure
Python Command Line window.

In command line mode, you type Python instructions one line


at a time.

IDLE (Integrated DeveLopment Environment)


Python IDLE comes with the standard Python distribution. IDLE
combines an interactive interpreter with code editing and debugging tools.
The Python IDLE Shell window as shown in Figure.

Python Shell window.

Character set:
Any Programming language is required to represent its
characters with the help of character set. An ASCII character set
is used to represent characters up to 3 rd generation
languages(c/c++). An ASCII character set supports 8 bit
characters. The number of characters that can be represented by
this coding system is limited to 256 only. In order to extend
ASCII coding system, an universal coding system (UNICODE)
is introduced. Python adapted this coding system for
representing its characters.

Keywords
Keywords are the reserved words in Python. There are 35 keywords in
Python 3.7.1 This number can vary in different versions of Python.

Keywords in Python programming language

False,None, True, and, as, assert, async,


await,break, class, continue, def, del, elif, else,
except, finally, for, from, global, if, import, in,
is, lambda, nonlocal, not, or,'pass, raise,
return,try, while, with, yield
Note:

You can always get the list of keywords in your current version by typing
the following in the prompt.

>>> import keyword


>>> print(keyword.kwlist)

Running Python as a calculator

Eg:
>>> 2*10
20
>>> 3+4+9
16
>>> 2**3
8
Data Types in Python
Python has a rich set of fundamental data types. The operations on an
object depend on its data type.

The list of data types are as follows:


Integers:
Integers are 32 bits long, and their range is from

–2,147,483,648 to 2,147,483,647`
Long Integers:
It has unlimited, subject to the memory limitations of the computer.

Floating Point Numbers:


Floating-point numbers are also known as double-precision numbers .(use
64 bits)

Strings:
Sequences of Unicode characters. A string can be represented either
Single quotes (or) double quotes.

Boolean:
It can hold only one of two possible values: True or False.

Complex Number:
A complex number has a real and an imaginary component, both
represented by float types in Python. For instance, 2+3j is a complex
number, where 3j is the imaginary component and is equal to
√-9 (√9 × √−1 = 3i or 3j)

Eg1:
>>> complex(2,3)
(2+3j)

Finding Data Types


To find the data type of the specified object, we use the type() function,
which returns the data type of the object passed to it.
Syntax:
type(value/object)
eg:
>>> type(10)
<class 'int'>

>>> type(10.0)
<class 'float'>

>>> type(‘abc’)
<class 'str'>

>>> type(True)
<class 'bool'>

>>> type(2+3j)
<class 'complex'>

Variables
Variables are used for storing data in a program. Therefore, by
assigning different data types to variables(you can store letters,
numbers, or words).
Rules for creating variable names(Identifiers)
1. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore ( _ ).
2. An identifier cannot start with a digit. identifier must start with a
letter or an underscore
3. Keywords cannot be used as identifiers.
4. Identifier can be of any length.

For example
A = 10
value = 10.0
st_value="Hello World!"

You can see in the preceding examples the variable can be a single
character or a word or words connected with underscores.

Multiple Assignment
Python allows you to assign a single value to several variables.
For example
a=b=c=1
Here, an integer value 1 is assigned all the three variables.
For example –
a,b,c=1,2,”Hello”
Here, two integer values 1 and 2 are assigned to variables a and b
respectively, and a string "Hello" is assigned to the variable c.

Python Input and Output


Python provides no. of built-in functions for I/O operations. Some of the
functions like input() and print() are widely used for standard input and
output operations . Let us see the output section first.
Python Output Using print() function
The 'print' function is used to print data to the standard output device .
Syntax:
print(objects, sep=' ', end='\n')

· Here, objects are the value(s) to be printed


(objects are separated by comma).
· The ‘sep’ is used to display separator between the values.
( default is a space character)
· After all values are printed, ‘end’ is printed.
(default is a new line).
eg:
print('Welcome')
Output: Welcome
a=5
print('The value of a is', a)
Output: The value of a is 5

print(1,2,3,4)
Output: 1 2 3 4

print(1,2,3,4,sep='*')
Output: 1*2*3*4

print(1,2,3,4,sep='#',end='$')
Output: 1#2#3#4$

Eg:2
print('Hello', 'welcome to python')
output: Hello welcome to python
It display the two strings on the same line separated by a space
print('Hello'+ 'welcome to python')
output: Hellowelcome to python
It display the two strings on the same line without any space in
between the two strings.

Formatting the Output


Sometimes we would like to format our output . This can be done by
using the str.format() method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
Output :The value of x is 5 and y is 10

Here the curly braces {} are used as placeholders. We can specify the
order in which it is printed by using index numbers.

Eg:
print('I love {0} and {1}'.format('bread','butter'))
Output: I love bread and butter
print('I love {1} and {0}'.format('bread','butter'))
Output: I love butter and bread

Comments:
Comments lines are for documentation purposes and
these lines are ignored by the interpreter.
# - Single line comment

’’’
---------------------
--------------------- Multi line comment
----------------------
’’’

Writing Python Programs(Scripts)


We can write Python programs either through IDLE’s built-in
editor or through any editor. We will be using IDLE’s editor for
writing programs. We can launch IDLE and then select the File >
NewFile option to open IDLE’s built-in editor and write the
following small program.
Note: Python script(program) extension is .py
test.py
# This is First program
print ("Hello World!")
print ("Welcome to Python Programming")

Running Python Programs from the IDLE’s editor


We can run the program from IDLE editor by pressing the F5
function key (or) from the editor’s Run menu: select Run Module.
The output appears in the IDLE interactive shell window.
P1.py
eno = 100 # An integer assignment
ename = "HHHH" # A string assignment
salary = 10000.0 # A floating point assignment
print("Eno :",eno)
print("Ename :", ename)
print("Salary :",salary)

Format strings
We can use format strings in print() function like printf() style used
in ‘C’ language.
The list of format Strings

Eg:
Emp.py
eno=100
grade='A'
ename='HHHH'
salary=20000.00
print ("Eno :%d" %(eno))
print ("Grade :%c" %(grade))
print ("Ename :%s" %(ename))
print ("salary :%.2f" %(salary))

Escape Sequences
Python uses some backslash characters in output functions for formatting the
output. These characters are called as Escape sequence characters. In these
characters it consists of two characters ,But it is treated as a single character

Eg:
print('Hello \n Welcome to Python Programming')
print('Name\tEmail Address\tContact Number')

python Input
We want to take the input from the user, We use input() function.
Syntax :
input([prompt])

where prompt is the string we wish to display on the screen. It is


an optional.

Note: input function return only string value.


>>> num = input('Enter any number: ')
Enter any number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number.

Type conversion(casting) in Python


Sometimes it is necessary to convert values from one type to another.
The process of converting from one type to another type is called as type
casting or type conversion.
To convert one type to another Python supplies several built-in functions.
these functions are

1) int(x)
This function converts any data type to integer.

2)float(x) :
This function is used to convert any data type to a floating point
number

Con1.py
s = input(‘Enter any string :”)
c = int(s)
print ("After converting to integer : ",c)
c = float(s)
print ("After converting to float : ",c)

3. ord(x) :
converts a character to integer.
4.chr(x) :
Converts an integer to a character
5. str(x) :
Converts integer (or) float into a string.
6.complex(real,imag) :
Converts real numbers to complex number

Con2.py
c = ord('d')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting character to integer :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integer to complex number :",c)

Python Indentation
Most of the programming languages like C, C++and Java use braces { }
to define a block of code. Python uses whitespace indentation to define
blocks rather than curly braces . A code block (body of
a function, loop etc.) starts with indentation and ends with un-indentation
line.

Continuation Lines
You can join two adjacent lines,the first ends with a backslash (\).
The indentation is not applied to continuation lines.
Eg:
print('Hello World! \
Welcome to \
PYTHON.')

Python Operators
Operator :
Operator is special symbol in Python and it performs a particular
operation.
Operand :
The value on which the operator acts is called as operand.
Python has a number of operators which are classified below.
1)Arithmetic operators
2)Relational operators
3)Logical operators
4)Bitwise operators
5)Assignment operators
6)Special operators
a. Identity operators
b. Membership operators

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.

Ari.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('Addition :',a+b)
print('Subtraction :',a-b)
print('Multiplication :',a*b)
print('Division :',a/b)
print('Modulus :',a%b)
print('Floor Division :',a//b)
print('Exponent :',a**b)

round()
Python provides an inbuilt function round() ,which rounds precision
digits of floating point number.
Syntax:
round(floating number, no of precision digits)

>>>round(10.639 , 2)
10.64

2)Relational operators
These are used to test the relation between 2 values or 2 expressions.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Logical operators :
These are used to combine the result of 2 or more expressions.
and Logical AND
or Logical OR
not Logical NOT

Exp1 Exp2 Exp1 and Exp2 Exp1 or Exp2


-----------------------------------------------------------------------
True True True True
True False False True
False True False True
False False False False

If Exp=True -> not Exp=False


If Exp=False -> not Exp=True

Bit-wise Operators :
These operators are used for manipulation of data at bit level.
Bit-wise logical operators :
These are used for bit-wise logical decision making.

& Bit-wise logical AND

Bit-wise logical OR

^ Bit-wise logical XOR


B1 B2 B1 & B2 B1 B2 B1 ^ B2
----------------------------------------------------------------------
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Eg : int a=5,b=6;
a=5 - 1 0 1
b=6 - 1 1 0

1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------

1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------

1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------

Bit1.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('a & b :',a&b)
print('a | b :',a|b)
print('a ^ b :',a^b)

Bit-wise shift operartor :


The shift operations take binary patterns and shift the bits to the left or
right.

<< - left Shift


>> - Right Shift
Eg :
a=4
a=4 -> 1 0 0 (binary form)
b=a<<2; means a is to be left shifted by 2 bits and store it in b.
then the value of b :-
1 0 0 0 0 = 2 power 4 = 16

a=4 -> 1 0 0 (binary form)


c=a>>1; means a is to be right shifted by 1 bit and store it in c.

then the value of c :-


1 0 = 2 power 1 = 2

Bit2.py
a=4
b=a<<2
c=a>>1
print('a :',a)
print('b :',b)
print('c :',c)

Assignment Operators :
These operators are used to assign values to variables.
Simple assignment :
=
compound assignment
+=
-=
*=
/=
//=
%=
**=
etc.
n=10, if we want to add 5 to n then we will give
n=n+5
(or)
n+=5 which is compound assignment.

Eg:
>>> n=10
>>> n
10
>>> n+=5
>>> n
15

Special operators
Python language offers two types of special operators. They are
1.identity operators
2.membership operators
Identity operators
‘is’ and ‘is not’ are the identity operators in Python. They are used to check
two values or variables.

is - True if the operands are identical


is not - True if the operands are not identical

eg:
>>> a=10
>>> b=10
>>> c=20
>>> a is b
True
>>> a is not c
True
Membership operators
‘in’ and ‘not in’ are the membership operators in Python.
They are used to test whether a value or variable is found in a
sequence(string, list, tuple, and set).

in - True if value/variable is found in the sequence


not in - True if value/variable is not found in the sequence
eg:

>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True

Control Flow Statements :


Conditional control statments
1.Simple if statement
It is a Conditional control statement in Python
The general form of the if statement is:
if condition :
block

• The reserved word if begins a if statement.


• The condition is a Boolean expression . A colon (:) must
follow the condition.
• The block is a block of one or more statements to be executed
if the condition is true.

- To find maximum value of given two values using simple if


If.py
print ("Enter any two values")
a=int(input())
b=int(input())
max=a
if max < b :
max=b
print("Maximum value :",max)

2. if-else statement
It is an extension of simple if statement.

The general form of an if-else statement is


if condition :
if block
else :
else block

The condition is a Boolean expression, if it is true then if block will be


executed otherwise else block will be executed.

- To find maximum value of given two values using if-else


If-else.py
print ("Enter any two values")
a=int(input())
b=int(input())

if a> b :
max=a
else :
max=b
print("Maximum value :",max)

- To check whether the given number is even or odd

if-else1.py
n=int(input("Enter any Number :"))
if n%2==0 :
print("Given Number is Even")
else :
print("Given Number is Odd")

3. Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.

Form : 1
if condition-1 :
if condition-2 :
………….
………..
If condition-n :
Statements

Form : 2
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
If condition-3 :
Statement-3
else :
Statement-4

To find maximum of three values


Nest-if.py

print("Enter any 3 values ")


a=int(input())
b=int(input())
c=int(input())
if a>b :
if a>c :
max=a
else :
max=c
else :
if b>c :
max=b
else :
max=c
print("Maximum value :",max)

4. if-elif-else statement
This statement is also used for a series of decisions are involved.

Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements

In this statement, the conditions are evaluated from top to bottom, if


the condition is true then the statements associated that block is executed
and the control transfers to the next statement. Otherwise when all
conditions are false then the final else block statements will be executed.

- Find maximum of 3 values using if-elif-else


If-elif.py
print("Enter any 3 values ")
a=int(input())
b=int(input())
c=int(input())
if a>b and a>c :
max=a
elif b>c :
max=b
else :
max=c
print("Maximum value :",max)

- write a python script to enter student number,name,marks in c,c++ ,


java and python . calculate and display total marks,average,result and
grade.

Stu.py
sno=int(input("Enter Student Number :"))
sname=input("Enter Student Name :")
print("Enter Marks in C,C++ ,Java and Python ");
c=int(input())
cpp=int(input())
java=int(input())
python=int(input())
tot=c+cpp+java+python
avg=tot/4
if c>=50 and cpp>=50 and java>=50 and python>=50 :
result='Pass'
if avg >=90:
grade='A+'
elif avg>=70:
grade='A'
else :
grade='B'
else :
result='Fail'
grade='-'
print(" RESULT ")
print("----------------------------------")
print("Sudent Number :",sno)
print("Sudent Name :",sname)
print("Marks in C :",c)
print("Marks in C++ :",cpp)
print("Marks in Java :",java)
print("Marks in Python :",python)
print("Total Marks in :",tot)
print("Average :%.2f" %(avg))
print("Result :",result)
print("Grade :",grade)
print("----------------------------------")

# To check whether the given character is alphabet or digit or special


character
char_ck1.py
print("Enter any character : ",end='')
ch=ord(input())
if (ch>=65 and ch<=90) or (ch>=97 and ch<=122) :
print("Given character is a alphabet")
elif (ch>=48 and ch<=57) :
print("Given character is a digit")
else :
print("Given character is a special character")

# To check whether the given character is vowel or consonant


char_ck2.py
print("Enter any character : ",end='')
n=ord(input())
if (n>=65 and n<=90) or (n>=97 and n<=122) :
ch=chr(n)
if ch in "AaEeIiOoUu" :
print("Given character is Vowel")
else:
print("Given chartacter is Consonant")
else:
print("Given character is not an Alphabet")
Loop control statements :
loop:
The process of repeatedly executing a block of statement up to
specified number of times is called as loop.
Python supports 2 types of looping statements. They are :
1) while loop
2) for loop

While loop
It is a conditional controlled loop statement in python.

Syntax:
while condition :
statements

In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the
condition will be evaluated once again, if it is true then the statement block
will be executed once again. This process of repeated execution continues
until the condition becomes false.

#To Display natural numbers from 1 to given number


n=int(input("Enter any Number :"))
print("Natural number from 1 to",n)
i=1
while i<=n :
print(i,end='\t')
i=i+1
#To Display Even and Odd numbers from 1 to given number
n=int(input("Enter any Number :"))
print("\nEven number from 1 to",n)
i=1
while i<=n :
if i%2==0 :
print(i,end='\t')
i=i+1
print("\n\nOdd number from 1 to",n)
i=1
while i<=n :
if i%2!=0 :
print(i,end='\t')
i=i+1

#To Display factors of given number


n=int(input("Enter any Number :"))
print("Factors of ",n)
i=1
while i<=n :
if n%i==0 :
print(i,end='\t')
i=i+1

#To check whether the given number is prime or not

print("Enter any Number : ",end='')


n=int(input())
count=0
i=1
while i<=n :
if n%i==0 :
count=count+1
i=i+1
if count==2 :
print("Given Number is Prime")
else :
print("Given Number is Not Prime")

#To calculate and display factorial of given number


n=int(input("Enter any Number :"))
fact=1
while n>=1 :
fact=fact*n
n=n-1
print("Factorial of Given Number :",fact)

#To calculate and display Reverse of given number


n=int(input("Enter any Number :"))
rev=0
while n>0 :
rev=(rev*10)+(n%10)
#n=int(n/10)
n=n//10
print("Reverse Number :",rev)

#To display Fibonacci series of first n terms


n=int(input("Enter No of Terms :"))
i,a,b,c=1,1,0,0
print("Fibonacci Series : ",end='')
while i<=n :
print(c,end="\t")
c=a+b
a=b
b=c
i=i+1

The range () Function


The range() function generates and returns a sequence of integers and
is very commonly used in for loop statement. There are 3 variations of the
range() function, depending on the number of parameters passed to it.

range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .

range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .
range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.

Note: When step is not specified, its default value is 1.

• range(10) -> 0,1,2,3,4,5,6,7,8,9


• range(1, 10) -> 1,2,3,4,5,6,7,8,9
• range(1, 10, 2) -> 1,3,5,7,9
• range(10, 0, -1) -> 10,9,8,7,6,5,4,3,2,1
• range(10, 0, -2) -> 10,8,6,4,2
• range(2, 11, 2) -> 2,4,6,8,10
• range(-5, 5) -> −5,−4,−3,−2,−1,0,1,2,3,4

The for Loop


The for loop iterates over a range of values. These values
can be a numeric range, or, elements of a data structure like a
string, list, tuple,etc.
Syntax:
for iterating_var in sequence:
statements

# To displays numbers from 1 to Given Number

n=int(input(“Enter any Number :”))


print(“Natural Number from 1 to”,n)
for i in range(1,n+1):
print (i,end='\t')

#To Display Even and Odd numbers from 1 to given number using for loop
n=int(input("Enter any Number : "))
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')

print("\n\nOdd number from 1 to",n)


for i in range(1,n+1,2):
print(i,end='\t')

Unconditional control statements


1. The break statement
The break statement terminates and exits from the current loop.
It is typically used in an infinite loop.
Syntax:
break

Infinite Loops
An infinite loop is a loop that executes its block of statements repeatedly
until the user forces the loop to quit2E

break.py
k=1
while True :
print (k,end='\t')
k=k+1
if(k>10):
break
Output:
1 2 3 4 5 6 7 8 9 10

2. The continue Statement


The continue statement stops execution of the current iteration by
skipping the rest of the loop and continuing to execute the loop with the
next iterative value.
Syntax:
continue

The following program prints numbers from 1 to 10 except for the values 4
and 7
continue.py
k=1
while k <=10 :
if k==4 or k==7:
k=k+1
continue
print (k,end=’\t’)
k=k+1
Output:
1 2 3 4 5 6 8 9 10

3. The pass Statement


The pass statement is used in Python to indicate an empty block of
statements.

pass.py
k=1
while k <=10 :
if k==7:
pass
else:
print (k,”\t”,end=’’)
k+=1
Output:
1 2 3 4 5 6 8 9 10

Nested loops
Using a loop statement within another loop is called as nested loops.

#To display Prime Numbers from 1 to given number .


Prime1.py
print("Enter any Number : ",end='')
n=int(input())
for i in range(1,n+1) :
count=0
j=1
while j<=i :
if i%j==0 :
count=count+1
j=j+1
if count==2 :
print(i,"\t",end='')
patteren1
n = int(input("Enter the value of n : "))
for i in range(1,n) :
j=1
while j<=i :
print('*',end=" ")
j=j+1
print()

patteren2
n = int(input("Enter the value of n : "))
s=n*2
for i in range(1,n) :
for k in range(1,s):
print(end=" ")
j=1
while j<=i :
print('*',end=" ")
j=j+1
print()
s=s-2

patteren3

n = int(input("Enter the value of n : "))


s=n*2
x=1
for i in range(1,2*n) :
for k in range(1,s):
print(end=" ")
j=1
while j<=x :
print('*',end=" ")
j=j+1
print()
if i<n :
s=s-2
x=x+1
else :
s=s+2
x=x-1+
Data Structures
1)Sequences
A sequence ia a collection objects . You can identify an object
in a sequence by its index.
Examples of sequences: lists, tuples, and strings.

2) Sets
3) Dictionaries
Note: Sets and Dictionaries are containers for sequential
data.
Lists
A list is a data structure in Python that is mutable (changeable)
sequence of elements. Each element or value that is inside of a
list is called an item. A list is created by placing all the items
(elements) inside a square brackets, separated by comma. It can
have any number of items and they may be of different types
(integer, float, string etc.).
Syntax:
List_Name = [item-1,item-2,………,item-n]

# empty list
a=[]

# list of integers
a = [1, 2, 3]

# list with mixed data types


a = [1, "Hello", 3.4]

Access Elements from a list


There are various ways in which we can access the elements of a list.
List Index
We can use the index value to access an item in a list.
List Index value starts from 0. So, a list having 5 elements ,will have
index from 0 to 4.
Eg:

>>> a = ['P','Y','T','H','O','N']
>>> a
['P', 'Y', 'T', 'H', 'O', 'N']

>>> print(a[2])
T
>>> print(a[5])
N

Sub lists
>>> a=[[1,2,3],[100,200,300]]
>>> a
[[1, 2, 3], [100, 200, 300]]
>>> print(a[0][1])
2
>>> print(a[1][2])
300

Negative indexing
Python allows negative indexing . The index of -1 refers to the last item, -2 to the
second last item and so on.
>>> a = ['P','Y','T','H','O','N']
>>> print(a[-1])
N
>>> print(a[-6])
P

Slicing
We can access a range of items in a list by using the slicing operator : (colon).
Syntax:
List_name[x:y]
It displays list Items from x to y-1;
>>> a=[10,20,30,40,50,60,70,80,90,100]
# elements 3rd to 5th
>>> print(a[2:5])
[30, 40, 50]

# elements beginning to 4th( index 0 to 4)


>>> print(a[ : 5])
[10, 20, 30, 40, 50]

# elements 6th to end


>>> print(a[5:])
[60, 70, 80, 90, 100]
# elements beginning to end
>>> print(a[:])
[10,20,30,40,50,60,70,80,90,100]

change elements in a list


List is mutable, means their elements can be changed .We can use
Assignment operator (=) to change an item or a range of items.
Eg:
>>> a=[2,5,7,8,10]
>>> a
[2, 5, 7, 8, 10]

# change the 1st item


>>> a[0]=1
>>> a
[1, 5, 7, 8, 10]

# change 2nd to 5th items


>>> a[1:5]=[2,3,4,5]
>>> a
[1, 2, 3, 4, 5]

Delete Elements from a List


We can delete one or more items from a list using the keyword del .
Eg:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]

>>> del a[1]


>>> a
[1, 3, 4, 5]

>>> a=['P','Y','T', 'H','O','N']


>>> a
['P', 'Y', 'T', 'H', 'O', 'N']
>>> del a[1:3]
>>> a
['P', 'H', 'O', 'N']

>>> del a
>>> a
NameError: name 'a' is not defined

List Methods
Some Methods are available with list object in Python programming
They are accessed as listobject .method()
1)append
Add an element to the end of the list
Syntax:
append(x)
x - element
Eg:
>>>a=[1,2,3]
>>> a
[1, 2, 3]
>>> a.append(4)
>>>a
[1, 2, 3, 4]

#Write a python script to accept a List from key board and display list elements
List1.py
n=int(input("Enter No of Elements :"))
a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given Elements :",a)

2)Insert
Insert an Element at given position(index).
Syntax:
insert(i, x)
i – index
x- element

Eg:
>>> a = [1,2,4,5,6]
>>> a
[1, 2, 4, 5, 6]
>>> a.insert(2,3)
>>> a
[1, 2, 3, 4, 5, 6]

Note: If the specified index is not available ,the element will be inserted at
last index.
>>> a.insert(20,100)
>>> a
[1, 2, 3, 4, 5, 6, 100]

Remove
Removes an Element from the list
Syntax:
remove(x)
x – element
Note:
1.It removes first occurrence of the specified element
2.if there is no such item, it displays an error
Eg:
>>> a = [1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.remove(2)
>>> a
[1, 3, 4, 5]
>>> a.remove(8)
ValueError: list.remove(x): x not in list

pop
Removes and returns an element at the given index in the list, and return it. If no
index is specified, It removes and returns the last item in the list.
Syntax :
Pop( [i] )
i – index
Eg:
>>> a = [1,2,3,4,5,6]
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop(3)
4
>>> a
[1, 2, 3, 5, 6]
>>> a.pop()
6
>>> a
[1, 2, 3, 5]
>>> a.pop(10)
IndexError: pop index out of range

clear
Removes all elements from the list.
Syntax:
clear()
Eg:
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.clear()
>>> a
[]

index
Returns the index of the First matched Element
Syntax:
index(x)
x – element

Eg:
>>> a=[1,2,5,2,8]
>>> a
[1, 2, 5, 2, 8]
>>> a.index(2)
1
>>> a.index(10)
ValueError: 10 is not in list

count
Return the number of times Element appears in the list.
Syntax:
count(x)
x – element

>>> a=[1,2,4,2,6,2]
>>> a
[1, 2, 4, 2, 6, 2]
>>> a.count(2)
3
>>> a.count(8)
0

extend
Extend the list by appending all the Elements from another list
Syntax:
extend(another list)

Eg:
>>> a=[1,2,3]
>>> b=[4,5,6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]

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

Sort
Sort Elements in a list in ascending or descending order.
Syntax:
sort([reverse=False])
sort() – ascending
sort(reverse=True) - descending

Eg:
>>> a=[5,2,6,1,4,3]
>>> a
[5, 2, 6, 1, 4, 3]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.sort(reverse=True)
>>> a
[6, 5, 4, 3, 2, 1]

#To accept a group of elements and display in Ascending order and Descending order
List_sort.py

n=int(input("Enter No of Elements :"))


a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given Elements :",a)
a.sort()
print("Given Elements in Ascending order :",a)
a.sort(reverse=True)
print("Given Elements in Descending order :",a)
reverse
Reverse order of the Elements in the list
Syntax:
reverse()
>>> a=[1,2,3,4,5]
>>> a
[1, 2, 3, 4, 5]
>>> a.reverse()
>>> a
[5, 4, 3, 2, 1]

Buit-in functions
1)len(list)
Gives the total length of the list.
2)max(list)
Returns the maximum element in the list.
3)min(list)
Returns the minimum element in the list.
4)sorted(list)
Returns the sorted list
Eg:
List_funs.py
n=int(input("Enter No of Elements :"))
a=[]
print("Enter Elements")
for i in range(n):
a.append(int(input()))
print("Given List :",a)
print("Length :",len(a))
print("Max Element :",max(a))
print("Min Element :",min(a))
print("Sorted List :",sorted(a))

Tuples
A tuple is a sequence of immutable Python objects. Tuples are just like
lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square
brackets.
Note: parentheses brackets are optional for Tuples
Syntax:
Tuple_name=(item-1,item-2,…,ietm-n)
Eg:
>>> tup1=('hari','ravi',100,200)
>>> tup1
('hari', 'ravi', 100, 200)

>>> tup2=(1,2,3,4,5)
>>> tup2
(1, 2, 3, 4, 5)

>>> tup3 = "a", "b", "c", "d"


>>> tup3
('a', 'b', 'c', 'd')

>>> t=tuple('PYTHON')
>>> t
('P', 'Y', 'T', 'H', 'O', 'N')

>>> print(t[0])
P
>>> print(t[1:3])

('Y', 'T')

>>> a=(1,2,3)

>>> b=(4,5,6)

>>> c=a+b

>>> c

(1, 2, 3, 4, 5, 6)
Buit-in functions
1)len(tuple)
Gives the total length of the tuple.
2)max(tuple)
Returns the maximum element in the tuple.
3)min(tuple)
Returns the minimum element in the tuple.
4)sorted(tuple)
Returns the sorted list of given tuple

Tup_fun.py
a=(3,6,1,8,4,5)
print("Given Tuple :",a)
print("Length :",len(a))
print("Max Element :",max(a))
print("Min Element :",min(a))
print("Sorted List :",sorted(a))

Strings

A string is a sequence of characters used to store text information. A


string can be enclosed in single quotes (') (or) double quotes (")

Eg:
st=' Hello World! '
st="Hello World!"

String functions

str:
Returns a string representation of the specified object.
Syntax:
str(x)
x – object of any datatype
eg:
>>> str(123)
'123'
>>> str(10.345)
'10.345'

max():
Returns the maximum alphabetical character in the string.
eg:
>>> max("ABCDEFGH")
'H'

min():
Returns the minimum alphabetical character in the string.
eg:
>>> min("ABCDEFGH")
'A'

len():
Counts and returns the number of characters in the string.
eg:
>>> len("ABCD")
4

sorted():
Returns the List representation string’s characters in sorted order.
>>> st="CFADEB"
>>> sorted(st)
['A', 'B', 'C', 'D', 'E', 'F']

String Methods

lower():
Returns the string converted to lowercase.
eg:
>>> st="WelCome"
>>> st.lower()
'welcome'

upper():
Returns the string converted to uppercase.
eg:
>>> st="WelCome"
>>> st.upper()
'WELCOME'

swapcase():
Returns the string with uppercase characters converted to lowercase and
lowercase characters converted to uppercase .

Eg:
>>> st="WELcome"

>>> st

'WELcome'

>>> st.swapcase()

'welCOME'

title():
Returns the string with first character of each word converted to uppercase
characters and the rest all characters in lowercase.

eg:
>>> st="welcome to python programming"
>>> st
'welcome to python programming'
>>> st.title()
'Welcome To Python Programming'

isalpha():
Returns True if all characters in the string are alphabetic, otherwise returns
False.
eg:
>>> st="abcd"
>>> st.isalpha()
True
>>> st="123abcd"
>>> st.isalpha()
False

isdigit():
Returns true if all characters in the string are digits, otherwise returns false.
eg:
>>> st="123"
>>> st.isdigit()
True
>>> st="123abcd"
>>> st.isdigit()
False

islower():
Returns true if all characters in the string are lowercase, otherwise returns false.
eg:
>>> st="abcd"
>>> st.islower()
True
>>> st="abcd123"
>>> st.islower()
True
>>> st="ABCD"
>>> st.islower()
False
>>> st="1234"
>>> st.islower()
False
>>> st="abcdABCD"
>>> st.islower()
False

isupper():
Returns true if all characters in the string are in uppercase, otherwise returns
false.
eg:
>>> st="ABCD"
>>> st.isupper()
True
>>> st="abcd"
>>> st.isupper()
False
>>> st="ABCD123"
>>> st.isupper()
True
>>> st="abcdABCD"
>>> st.isupper()
False
>>> st="1234"
>>> st.isupper()
False

Sets
A set is a collection of values(elements)with no duplicate elements.
This is based on a data structure known as a hash table. Sets support
mathematical operations like union, intersection, difference, and symmetric
difference. Curly braces or the set() function can be used to create sets.
Syntax :
1)Set_name={item-1,item-2,..,item-n}
2)set_name = set([Sequence])

Eg:
>>> a={1,2,3,4,5}
>>> a
{1, 2, 3, 4, 5}

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

>>> s=set([3,1,5,4])
>>> s
{1, 3, 4, 5}

Python Set Operations


Sets can be used to perform mathematical set operations like union,
intersection, difference and symmetric difference. We can do this with
operators or methods.
Set Union
Suppose A and B are two sets, Union of A and B is a set of all elements from both sets.
Union is performed using | operator. Same can be accomplished using the
method union().

Set1.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)

Output: {1, 2, 3, 4, 5, 6, 7, 8}
Syntax of Union Method:

union(Another set)

Eg:
>>> a={1,3,5,7,9}
>>> b={1,2,3,4,5}

>>> a.union(b)
{1, 2, 3, 4, 5, 7, 9}
>>> b.union(a)
{1, 2, 3, 4, 5, 7, 9}

>>> a={1,2,3,4,5}
>>> b={4,5,6,7,8}
>>> c={6,7,8,9}
>>> print(a|b|c)
{1, 2, 3, 4, 5, 6, 7, 8, 9}

Set Intersection
Intersection of A and B is a set of elements that are common in both sets.
Intersection is performed using & operator. Same can be accomplished using the
method intersection() .

>>>A = {1, 2, 3, 4, 5}
>>>B = {4, 5, 6, 7, 8}
>>>print(A & B)
{4, 5}
Eg:
>>> A.intersection(B)
{4, 5}

Set Difference
Difference is performed using '-' operator. Same can be accomplished using the
method difference() .
Difference of A and B ( A - B ) is a set of elements that are only in A but not in B .
Similarly, B - A is a set of elements in B but not in A .
Eg:
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
>>> print(A - B)
{1, 2, 3}
Eg:
>>> A.difference(B)
{1, 2, 3}

Set Symmetric Difference


Symmetric Difference of A and B is a set of elements in both A and B except those
that are common in both.
Symmetric difference is performed using ^ operator. Same can be accomplished using
the method symmetric_difference() .
Sdiff.py
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output: {1, 2, 3, 6, 7, 8}

Eg:
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}

Python Set Methods


1) add
Add an element to a set
Syntax :
add(element)
Eg:
>>> A={1,2,3,4}
>>> A
{1, 2, 3, 4}
>>> A.add(5)
>>> A
{1, 2, 3, 4, 5}

2) clear
Remove all elements from a set
Syntax:
clear()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.clear()
>>> A
set()

3) pop
Remove and return first set element.
Syntax:
pop()
Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.pop()
1
>>> A
{2, 3, 4, 5}

5) remove
Remove an element from a set.
Syntax:
remove(element)

Eg:
>>> A={1,2,3,4,5}
>>> A
{1, 2, 3, 4, 5}
>>> A.remove(3)
>>> A
{1, 2, 4, 5}
>>> A.remove(8)
KeyError: 8

Set_ope.py

a=set()
print("Enter First Set")
while True:
a.add(int(input()))
ch=input("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
b=set()
print("Enter Second Set")
while True:
b.add(int(input()))
ch=input("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
print("First set :",a)
print("Second set :",b)
print("Union of Two Sets :",a|b)
print("Intersection of Two Sets :",a&b)
print("Difference of Two Sets :",a-b)
print("Symmetric Difference :",a^b)

Built-in functions
1)len(set)
Returns the number of items in the set.
2)max(set)
Returns the maximum element in the set.
3)min(set)
Returns the minimum element in the set.
4) sum(set)
Returns the sum of items in the set.
5)sorted(set)
Return a new sorted list from elements in the set

Eg:
Set_fun.py
s=set()
print("Enter Elements")
while True:
s.add(int(input()))
ch=input(("Enter Anohter Element(y/n) :")
if(ch=='n'):
break
print('Given set is :',s)
print ('Length of set is :', len(s))
print ('Maximum value is :' , max(s))
print ('Minimum value is :' , min(s))
print ('Sum of items in set is :', sum(s))

Dictionaries
Python dictionary is an unordered collection of items. Creating a dictionary is placing
items inside curly braces {} separated by comma. An item has a key and the
corresponding value expressed as a pair. Each key is separated from its value by a
colon ( key : value ).

Syntax:
Dictionary_name = { key-1: value-1, key-2: value-2,….., key-n: value-n}
-
Eg1:
>>> d = {'a':10, 'b':1, 'c':22}
>>> d
{'a': 10, 'b': 1, 'c': 22}

Eg2:
>>> d = {'Name': 'Harsha', 'Age': 6, 'Class': 'First'}
>>> print (d['Name'])
Harsha
>>> print (d['Age'])
6
>>> print (d['Class'])
First

Updating Dictionary
Eg1:
>>> d = {'Name': 'Hari', 'Age': 7, 'Class': 'First'}
>>> d
{'Class': 'First', 'Name': 'Hari', 'Age': 7}
>>> d['Age'] = 8
>>> d['School'] = "ABC School"
>>> d
{'Class': 'First', 'Name': 'Hari', 'Age': 8, 'School': 'ABC School'}

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions−
Sr.No. Function with Description

1 len(dict)
Gives the total length of the dictionary.
2 str(dict)
Produces a string representation of a dictionary

Python includes following dictionary methods


Sr.No. Methods with Description

1 clear()
Removes all elements of dictionary
2 items()
Returns a list of dict's (key, value) tuple pairs
3 keys()
Returns list of dictionary dict's keys
4 values()
Returns list of dictionary dict's values

Eg1:
>>> dict = {'a':10, 'b':20, 'c':30}
>>> dict
{'a': 10, 'b': 20, 'c': 30}
>>> len(dict)
3
>>> str(dict)
"{'b': 20, 'a': 10, 'c': 30}"

Eg2:
d = {'a':10, 'b':1, 'c':22}
>>> d.items()
dict_items([('a', 10), ('b', 1), ('c', 22)])

Eg3:
>>> dict.values()
dict_values([20, 10, 30])
>>> dict.items()
dict_items([('b', 20), ('a', 10), ('c', 30)])
>>> dict.keys()
dict_keys(['b', 'a', 'c'])
>>> dict.clear()
>>> dict
{}

Note:
Arrays
Arrays are fundamental part of most programming languages. It is
the collection of elements of a single data type. However, in Python,
there is no native array data structure. So, we use Python lists instead
of an array.
Functions and Modules
Function
A function is a group of statements that can be invoked any
number of times. Besides the built-in functions, you can define
our own functions. In Python, a function always returns a value.

The 'def' Statement


The def statement is used to define a function.

Syntax:
def function-name( [parameter list] ):
statement(s)

function-name : It is an identifier to recognize the function.


Parameter list : It is an optional list of identifiers that are bound to the
values supplied , while calling the function.

The 'return' Statement


The return statement is used for returning value from the function. When
return executes, the function terminates, and the return value is passed to
the caller. When there is nothing to be returned to the caller, the function
returns ‘None’.

Eg1:
To Find sum of two objects
Func1.py
def sum(x,y):
return x+y

print("Enter any two values ")


a=int(input())
b=int(input())
print (sum(a,b))
print(sum("wel","come"))
print(sum([1,2,3],[4,5,6]))

Eg2:
To find maximum value of given two values
fun2.py

def maxval(x,y):
if x>y :
return x
else :
return y

print("Enter any two values")


a=int(input())
b=int(input())
m=maxval(a,b)
print ("Maximum value :",m)

Default Value Parameters


The parameters listed in the function definition may be mandatory or
optional. The mandatory parameters are those whose value has to be
supplied when calling the function. The optional parameters(default value
parameters) are those whose value may or may not be passed when calling
the function. An optional parameter is defined with the following syntax:

def func_name(identifier-1,identifier-2=value,…) :
statements

Here identifier-1 is mandatory parameter and identifier-2 is default value(optional)


parameter

Eg3:
Func3.py
def sum(x, y=20):
return x+y

print (sum(10))
print (sum(100,200))

Keyword Arguments
A value passed to a parameter by referring to its name is known as a
keyword argument.

Kwarg.py

def maxval(x,y=10,z=20):
if x>y and x>z :
return x
elif y>z :
return y
else :
return z

print("Maximum value :",maxval(30))


print("Maximum value :",maxval(y=15,x=5))
print("Maximum value :",maxval(x=40,z=20,y=50))

output:
Maximum value : 30
Maximum value : 20
Maximum value : 50

Local and Global Variables


Local variables have scope within the body of the
function in which they are defined. That is, local variables
are accessible inside the function. Global variables are
accessible inside and outside the functions.
Note :
Global variables are declared using the keyword global
global_var.py

def compute():
global x
print ("Value of x in compute function is", x)
x=x+5

def dispvalue():
global x
print ("Value of x in dispvalue function is", x)
x=x-2

x=0
compute()
dispvalue()
compute()
print ("Value of x outside functions is", x)

output:
Value of x in compute function is 0
Value of x in dispvalue function is 5
Value of x in compute function is 3
Value of x outside functions is 8

Local_var.py
def compute(x):
x=x+5
print ("Value of x in function is", x)

x=10
compute(x)
print ("Value of x is still", x)

output:
Value of x in function is 15
Value of x is still 10

Lambda Function
A lambda function is an anonymous function.
The body of the lambda function is small, a single
expression.

Consider a small function that multiplies a passed


argument by 2 and returns, as shown here

def func(x) :
return x*2

n=func(3)
print(n)
output:
6

You can rewrite this function as a lambda function:


Syntax:
Identifier=lambda arglist : expr

func=lambda x: x*2

n=func(3)
print(n)

output:
6

#To Display natural numbers from 1 to given number using user defined
function
ndisp.py
def display(x) :
for i in range(1,x+1):
print(i,end='\t')

n=int(input("Enter any Number :"))


print("Natural number from 1 to",n)
display(n)

#To calculate and Display factorial of given number using user defined
function

def factorial(x) :
f=1
while x>=1 :
f=f*x
x=x-1

return f

n=int(input(“Enter any Number :”))


fact=factorial(n)
print("Factorial of given Number :”,fact)

#To Display Reverse Number of a given Number using user defined


function

def reverse(x) :
rev=0
while x>0 :
rev=(rev*10)+(x%10)
x=x//10
return rev
n=int(input("Enter any Number :"))
r=reverse(n)
print("Reverse Number :",r)

- To Display Fibonacci Series of first n Terms using user defined


function

def fibo(x) :
a,b,c=1,0,0
for i in range(x):
print(c,end="\t")
c=a+b
a=b
b=c

n=int(input("Enter No of Terms :"))


print("Fibonacci Series : ",end='')
fibo(n)

Function Attributes
In Python, functions are treated as objects, A function object
has a number of attributes that you can use to get more
information about a function.
A list of function attributes are shown in below Table
fun_att.py

def sum(a, b=5):


''' adds the two numbers '''
return a + b
k=sum(10,20)
print ('Sum is', k)

print('The documentation string is', sum.__doc__)


print('The function name is', sum.__name__)
print('The default values of the function is', sum.__defaults__)
print('The default module of the function is', sum.__module__)

Recursive function
a function calls itself is called as Recursive function.
A function calling itself will generate an infinite loop, so when
implementing recursion, an exit condition must be included in the
function.

Note :
Recursion is implemented with the help of a data structure known
as a stack

#To Display natural numbers from 1 to given number using recursive function

def display(x):
if x > 1:
display(x-1)
print(x,end='\t')

n=int(input("Enter any Number :"))


print("Natural number from 1 to",n)
display(n)

#To calculate and Display factorial of given number using recursive function
def fact(x) :
if x<=1 :
return 1;
else :
return x * fact(x-1)

n=int(input("Enter any Number :"))


f=fact(n)
print("Factorial of given Number :" ,f)

Modules
A module is a file consisting of a few functions ,variables and classes
used for a particular task. A module can be imported in any program and
can be used it. The filename of the module must have .py extension.

To import a module to a program, We use the import statement.


Syntax :
Form1 : import module-1[,module-2,..,module-n]
It imports single module or group of modules
Form2 : from module import name-1[,name-2,..,name-n]
It imports specific attribute from specified module

Form3 : from module import *


It imports all attributes from specified module

Form 4: import module as name


It imports and temporarily rename the module.

Pre-defined Modules

Calendar module
It is used to display a calendar of a specified Year or Month.
Eg:
import calendar
prcal
It is a method and is used to display calendar of specified year
(default 3 months in a row)
Syntax:
prcal( year,m=3)
eg:
calendar.prcal(2018)
calendar.prcal(2018,m=2)

month
It is a method and is used to display calendar of specified year and
month
Syntax:
month(year,month)
Eg:
print(calendar.month(2018,3))

eg:
>>> from calendar import prcal
>>> prcal(2018)

>>> from calendar import *


>>> prcal(2018)
>>> import calendar as cal
>>cal.prcal(2018)

cal1.py
import calendar
year = int(input("Enter Year :"))
calendar.prcal(year)

cal2.py
import calendar
year = int(input("Enter Year :"))
month = int(input("Enter month :"))
print(calendar.month(year,month))

time module
ctime :
It is a method and is used to display current date and time
Eg:
import time
time.ctime()
o/p: 'Fri Apr 26 10:47:19 2019'

math Module

pi—Returns the value of pi,( 3.1415926535897931).


ceil(x)—Returns the next larger whole number.
floor(x)—Returns the next smaller whole number
sqrt(x) - Returns square root of given number
pow(x,y) - It calculates exponentional value of given base and power
(x-base,y-power)

mth.py
import math
print("pi = ",math.pi)
print("pi = ",round(math.pi,2))
print("Ceil value of 7.3:",math.ceil(7.3))
print("Floor value of 7.3 :",math.floor(7.3))
print("Square root of 9:",math.sqrt(9))
print("pow of 2 and 3 :",math.pow(2,3))

eval
Returns a result of the evaluation of a Python expression.

Syntax
eval (expression)
eg:
>>> x = 1
>>> eval('x+1')
2
>>> eval('2*2')
4

random module

The choice () Function


The choice() function picks and returns a random item from a sequence.
It can be used with lists, tuples, or strings. This Method belongs to random
module, so we import choice from random.
Syntax:
choice(sequence)

Example:
from random import choice
choice([2,4,6,8,10])
You will get a random value picked from the specified sequence, which
may be 2, 6, or some other value from the list.

rand1.py
from random import choice
k=choice([2,4,6,8,10])
print ("Random number is",k)
Output:
Random number is 4
rand2.py
from random import choice
ch='y'
while ch=='y' :
k=choice(range(1,10))
print ("Random number is ",k)
ch=input("Do you want to Continue(y/n) :")

The dir() Function


The dir() function is used to list the identifiers defined by a module. The
identifiers are the functions,classes, and variables defined in that module.
Syntax:
dir(module_name)

eg:

>>> import calendar


>>> dir(calendar)

>>> import math


>>> dir(math)

exit
It is method belongs to sys module, it terminates the program.
Syntax:
sys.exit()

Creating Userdefined Module


Create a file with extension .py and then define some functions, variables
and classes in that file(module).After creating the file(module) then import
that module and use functions, variable and classes in that module.

mymodule.py
def wel() :
print("Welcome to Python Modules")

x=10
y=20

>>> import mymodule


>>> mymodule.wel()
Welcome to Python Modules
>>> mymodule.x
10
>>> mymodule.y
20

Command-line Arguments
Command-line arguments are used to pass arguments to a program
while running it. Each command line argument that you
pass to the program will be stored in the sys.argv variable.
(sys is a module).

The sys.argv is a list that always has a length of at least 1, the item at
index 0 is the name of the Python program you are running.

Note: Command-line arguments are separated by space.

commandline1.py
import sys
print ('There are %d arguments' % len(sys.argv))
print ('The command line arguments are:' )
print (sys.argv)
for i in sys.argv:
print(i)
Object Oriented Programming
Object oriented programming introduced in 1980’s by
Bjarne Stroustrup. OOP'S improves the style of a program. It allows the
user to develop a program structure. This concept mainly introduces a
mechanism called class.

Basic concepts of Object Oriented Programming

1. Objects
2. Classes
3. Data encapsulation and Data abstraction
4. Inheritance
5. Polymorphism
Objects :
Objects are the runtime entities in object oriented programming. They
may represents a person, a place, etc. that are program has to handle.
They may also represent user defined data.

Classes :
The objects contain data and code to manipulate that data, the entire set
of data and code of an object can be made a user defined data type such
as class. Once a class has been defined, we can create any number of
objects belongs to that class.

Data encapsulation and Data abstraction :


Data encapsulation : ( Data hiding)
It is a mechanism that associates the code and data manipulations
into a single unit and keeps them safe from external interface. This is
supported by the construct called class.
The use of encapsulation is to protecting the members of a class. The
data is not accessible to the outside class and only those functions which
are wrapped (i.e. within the class) in the class can access it. This insulation
of data from direct access by the program is called as Data hiding.

Data abstraction:
abstact data type: a set of operations performed on a particular data
type is known as abstract data type.
The technique of creating new abstract data types that are well suited to
an application is known as data abstraction.
Data abstraction means we can combine the data structures and
operations on the data structures together into a new abstract data type.
An abstract data type not a part of language definition, they are created
by the user.

Inheritance :
It is a mechanism which is used to extend the definition of existing
class. The extension can be done by declaring some other class. The class
that is originally present is called as Base/super class and the class which is
extended with the help of inheritance is called as Derived/sub class. A
derived class always can access the members of base class, whereas a
base class never access the members of derived class. The main purpose
of inheritance is reusability of definition that is already made.

Polymorphism :
The word polymorphism is derived from 2 latin Words
1. Poly (many)
2. Morphs (forms)
Polymorphism is nothing but the ability to access different
implementations of the function using the same name.
There are 2 levels at which polymorphism operates.
1. Compile time polymorphism
2. Run time polymorphism

Classes and Objects


The Class Statement
Python supports object-oriented programming and provides reusable
code in the form of classes. A class is like a template or blueprint for data
and operations. It consists of a number of attributes that include variables
and methods(functions). The variables are called data members, and
methods are called member functions.

Syntax:
class classname[ (base classes) ] :
statements

where classname is an identifier that is bound to the class object. You can create
either an independent class or inherits from other classes.

Built-In Class Attributes


A class statement implicitly sets some class attributes. You can use these class
attributes to get information about a class.
cls_att.py
class test:
'''This is Sample class '''
pass
print ("Class name :", test.__name__)
print ("Base-classes :", test.__bases__)
print ("Doc String :", test.__doc__)
print ("Module :", test.__module__)

Defining Functions in a Class


The functions defined in a class are known as methods. A method is
defined in a class always has a mandatory first parameter named
'self' ,that refers to the instance (object) on which you call the method.

class classname [(base-classes)]:

class variable(s)

def method-1(self [,parameters]):


instance variable(s)
statement(s)
……………………
……………………
def method-n(self[,parameters]):
instance variable(s)
statement(s)
A class can have two types of data members(variables):
1. Class variable :
The data member that is outside of any method of the class is known as
a class variable. All instances of the class share the class variables, and
changes made in the class variable , that changes will be seen in all
instances.

2. Instance variable:
The variables that are defined inside a method are known as instance
variables. Changes made to instance variables by any instance are limited
to that particular instance and don’t affect other instances.

Instances(objects)
A class is a template or blueprint of data and operations.To
use the data and operations, you need to create instances. An
instance is a variable of a class. You can create as many
instances of a class and each instance gets a separate copy of the
methods and attributes defined in the class(except class
variables, class methods). Each instance can access the methods
and attributes of the class independently.

Syntax for create an instance of a class

identifier = class_name([parameter list])

identifier – Instance(object) name

Accessing Class Variables


Class_var.py
class num :
n=10

ob1=num()
ob2=num()
print("Initial value in the class valriable :",num.n);
print("Initial value in the First Object :",ob1.n)
print("Initial value in the Second Object :",ob2.n)
num.n=100
print(" value in the classvalriable :",num.n);
print("value in the First Object :",ob1.n)
print("value in the Second Object :",ob2.n)

Accessing Instance Variables


Instance_var.py
class num :

def datainput(self):
self.n=int(input())

def output(self) :
print(self.n)

ob1=num()
ob2=num()
print("Enter the value into First Object :",end='')
ob1.datainput()
print("Enter the value into Second Object :",end='')
ob2.datainput()

print("Given value in the First Object :",end='')


ob1.output()
print("Given value in the Second Object :",end='')
ob2.output()

The __init__() Method


---------------------------------
The __init__ method is the first method to be executed after creation of
an instance. This method is like a constructor in C++ and Java languages
and is used to perform initialization.

rectar1.py
class rect:
def __init__(self):
self.l = 8
self.b = 5
def rectarea(self):
return self.l * self.b

r=rect()
print ("Area of rectangle is ", r.rectarea())

Passing Arguments to __init__ Method


----------------------------------------------------
rectar2.py

class rect:
def __init__(self, x,y):
self.l = x
self.b = y

def rectarea(self):
return self.l * self.b

print("Enter Length and breadth of Rectangle");


ln=int(input())
br=int(input())
r=rect(ln,br)
print ("Area of rectangle is ", r.rectarea())

Defining Default Value Parameters in the __init__ Method


------------------------------------------------------------------------
rectar3.py
class rect:
def __init__(self,x=8, y=5):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b

r=rect()
s=rect(10,20)
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", s.rectarea())

__del__ Method
------------------
It is Called when the instance is to be destroyed.
This is also called as destructor.

del statement
del is a statement and is used to delete (destroyed) specified object.
Syntax:
del object_name

destructor.py
class test:
def __init__(self):
print("Instace (object) is Created")

def __del__(self):
print ("Instace (object) is destroyed")

t=test()
del t

Access Control Specifiers


Access control specifiers define the visibility of the members of the class.
All the members of the class are assigned a boundary in which they can be
accessed using these control specifiers. There are two types of Access
Control Specifiers public and private.
Public
Public member Accessed from inside as well as outside
of the class.
Private
Private member Cannot be accessed from outside the the class.
A private member is preceded by a double underscore (__).

Accessing public Members

Publicaccess.py
class rect:
def __init__(self, x,y):
self.l = x
self.b = y
def rectarea(self):
return self.l * self.b

r=rect(5,8)
print ("Area of rectangle is ", r.rectarea())
print ("Area of rectangle is ", r.l* r.b)

Accessing private Members


privateaccess.py
class rect:
def __init__(self, x,y):
self.__l = x
self.__b = y

def rectarea(self):
return self.__l * self.__b

r=rect(5,8)
print ("Area of First rectangle is ", r.rectarea())
s=rect(10,20)
'''
print ("Area of Second rectangle is ", s.__l* s.__b)
It is not possible,Because l abd b are private members
'''
print ("Area of rectangle is ", s.rectarea())

Class Methods
A class method has no self argument and receives a class(cls) as its first
argument. The class method can also be called directly through the class
name without instance. A class method is defined using the
' @classmethod ' decorator.

Syntax:
@classmethod
def method_name(cls,[arg-list]) :
statements

classmethod.py

class book:
price=100

@classmethod
def display(cls):
print (cls.price)

def show(self,x):
self.price=x
print (self.price)

book.display()
# book.show(200) It is not working ,because it not class method
b=book()
b.show(200)
Static Methods
A static method is an ordinary function that is built using the
@staticmethod decorator . The difference between a static method and a
class method is that a static method has no cls argument. This method can
also be called directly through the class name without instance.

Syntax:

@staticmethod
def method_name([arg-list]) :
statements

staticmethod.py

class book:
price=100

@staticmethod
def display():
print (book.price)

book.display()
Garbage Collection
Garbage collection is a procedure of freeing up the memory. The
memory that is used by the instances are usually freed up automatically .
That’s why memory leaks are rare in Python.

stu_cl.py
class student :

def datainput(self) :
self.sno=int(input("Enter Student Number :"))
self.sname=input("Enter Student Name :")
print("Enter Marks in C,C++,Java and Python ")
self.c=int(input())
self.cpp=int(input())
self.java=int(input())
self.python=int(input())

def calculate_result(self) :
self.tot=self.c+self.cpp+self.java+self.python
self.avg=self.tot/4
if self.c>=50 and self.cpp>=50 and self.java>=50 and self.python>=50
:
self.result='Pass'
if self.avg >=90 :
self.grade='A+'
elif self.avg>=70 :
self.grade='A'
else :
self.grade='B'
else :
self.result='Fail'
self.grade='No Grade'

def printresult(self) :
print(" RESULT ")
print("------------------------------------")
print("Sudent Number :",self.sno)
print("Sudent Name :",self.sname)
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)
print("Marks in python :",self.python)
print("Total Marks in :",self.tot)
print("Average : %.2f" %(self.avg))
print("Result :",self.result)
print("Grade :",self.grade)
print("-------------------------------------")

s=student()
s.datainput()
s.calculate_result()
s.printresult()

Inheritance
It is a mechanism which is used to extend the definition of an existing
class. The extension can be done by declaring some other class. The class,
that is originally present is called as “super class” or "Base class" and the
class which is extended with the help of inheritance is called “sub class” or
derived class . A sub class always access the members of super class,
whereas the super class never access the members of sub class. The main
purpose of inheritance is the reusability of definition that are already made.

Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
Single Inheritance
This is the simplest type of inheritance, where one class is derived from
another single class.

class B inherits class A, (or)


class B is derived from class A.

inr1.py
class base :
def __init__(self):
self.n=100
def display(self):
print("Initial value :",self.n)

class derv(base):
pass

d=derv()
d.display()

inr11.py
class base :

def accept(self):
self.n=int(input("Ennter any Number into base member :"))
def display(self):
print("Given value in the base member :",self.n)

class derv(base):

def datainput(self):
self.m=int(input("Enter the value into derv memeber :"))

def dataoutput(self):

print(" Given value in the derv member :",self.m)

d=derv()
d.accept()
d.datainput()
d.display()
d.dataoutput()

Method Overriding
If methods are defined with the same name both in base class and
derived classes, a derived class object always gives preference to the
derived class methods by overlooking base class methods. Hence it is
called overriding .
Invoking the overriding methods by the following way :
class_name . method_name([arg_list])
Note : This Syntax works only inside methods of derived class

inr2.py
class base :
def __init__(self):
self.n=100
def display(self):
print("Initial value in Base member :",self.n)

class derv(base):
def __init__(self):
base.__init__(self)
self.m=200

def display(self):
base.display(self)
print("Initial value in derv member :",self.m)

d=derv()
d.display()

inr22.py

class base :

def accept(self):
self.n=int(input("Ennter any Number into base member :"))

def display(self):
print("Given value in the base member :",self.n)
class derv(base):

def accept(self):
base.accept(self)
self.m=int(input("Enter the value into derv memeber :"))

def display(self):
base.display(self)
print(" Given value in the derv member :",self.m)
d=derv()
d.accept()
d.display()

Multilevel Inheritance
The mechanism of deriving a class from another derived class is called as
multi level inheritance.

inr3.py

class base :
def __init__(self):
self.a=100
def display(self):
print("Initial value in Base member :",self.a)
return None

class derv1(base):
def __init__(self):
base.__init__(self)
self.b=200

def display(self):
base.display(self)
print("Initial value in derv1 member :",self.b)
return None
class derv2(derv1):
def __init__(self):
derv1.__init__(self)
self.c=300

def display(self):
derv1.display(self)
print("Initial value in derv2 member :",self.c)
return None

d=derv2()
d.display()

Multiple Inheritance

One derived class with several base classes is called as multiple


inheritance.

Inr44.py
class base1 :
def __init__(self):
self.a=100

def display(self):
print("Initial value in Base1 member :",self.a)

class base2 :
def __init__(self):
self.b=200

def display(self):
print("Initial value in Base2 member :",self.b)

class derv(base1,base2):
def __init__(self):
base1.__init__(self)
base2.__init__(self)
self.c=300

def display(self):
base1.display(self)
base2.display(self)
print("Initial value in derv member :",self.c)

d=derv()
d.display()

inr4.py

class student:
def accept(self):
print("Enter Student Number :",end='');
self.sno=int(input())
print("Enter Student Name :",end='');
self.sname=input()

def display(self):
print("Sudent Number :",self.sno)
print("Sudent Name :",self.sname)

class marks :
def accept(self):
print("Enter Marks in C,C++ and Java ");
self.c=int(input())
self.cpp=int(input())
self.java=int(input())
def display(self):
print("Marks in C :",self.c)
print("Marks in C++ :",self.cpp)
print("Marks in Java :",self.java)

class result (student,marks):


def cal_result(self):
student.accept(self)
marks.accept(self)
self.tot=self.c+self.cpp+self.java
self.avg=float(self.tot/3)
if self.c>=50 and self.cpp>=50 and self.java>=50 :
self.result='Pass'
if self.avg >=90 :
self.grade='a+'
elif self.avg>=70 :
self.grade='A'
else :
self.grade='B'
else :
self.result='Fail'
self.grade='No Grade'
def display(self):
print(" RESULT ")
print("--------------------------------------------------")
student.display(self)
marks.display(self)
print("Total Marks in :",self.tot)
print("Average :%.2f" %(self.avg))
print("Result :",self.result)
print("Grade :",self.grade)
print("---------------------------------------------------")

s=result()
s.cal_result()
s.display()

Hierarchical Inheritance
One class may be inherited by more than one class. This process is called as
hierarchical inheritance. i.e. one base class with several derived classes.

Inr45.py
class base :
def __init__(self):
self.a=100

def display(self):
print("Initial value in Base member :",self.a)

class derv1(base) :
def __init__(self):
base.__init__(self)
self.b=200

def display(self):
base.display(self)
print("Initial value in derv1 member :",self.b)

class derv2(base):
def __init__(self):
base.__init__(self)
self.c=300

def display(self):
base.display(self)
print("Initial value in derv2 member :",self.c)

d1=derv1()
d2=derv2()
d1.display()
d2.display()

File Handling
In Python a file is a container for a sequence of data objects,
represented as sequences of bytes. File handling is a technique
by which you can store data and can retrieve it later.
When you run a program, the processed data is displayed on
the screen and temporally stored in RAM, so if later you want to
see the data, you can’t get it. To overcome these problems we
use files.

Text files :
These are used for reading and writing data in the form of characters.
Binary files :
These are used for reading and writing data in the form of data blocks.

The following three steps are required for working with files:
1. Opening a file
2. Performing actions on the file (reading, writing, updating contents)
3. Closing the file

Opening a File
open()
It is a function and it opens a file
Syntax:
open(filename, mode)

‘filename’ represents the name of the file, and ‘mode’ specifies the
purpose for opening the file. The open() function returns a file handler that
represents the file on the disk drive.

File modes
Note :
To open a Binary file append ‘b’ to the mode string
Eg: ‘wb’,’rb’,etc.

File Methods Used in Python

close() : Closes the file

read([n]) : Reads the n number of characters or bytes


from the file. If the optional value n is
omitted, the rest of the file is read.

readline([n]) : Reads n number of characters in the line from the file.


If n is omitted, the next complete line is read.

readlines() : Read all lines from the file and returns a list

write(string) : Writes the given string to the file.


writelines(list) : Writes the list of strings to the file.

seek(offset,location) : Sets the location of file handler at the


specified offset.
offset : Difference in bytes between location and new position

location :
0 - beginning of the file.
1 - current position.
2 - end of the file.

tell() : Returns the position of the file handler.

Textfile Operations

Writing and reading text data


file1.py

matter = '''Python is a great language


Easy to understand and learn
Supports Object Oriented Programming
Also used in web development '''

f = open('pyt.txt', 'w')
f.write(matter)
f.close()

f = open('pyt.txt','r')
lines = f.read()
print (lines)
f.close()
Reading line by line Data from a File
File2.py

f = open('pyt.txt','r')

while True:
line = f.readline()
if len(line) == 0:
break
print (line)

File Attributes

name : This attribute is the filename that was passed to


the open() function when creating the file object.

mode : This attribute is the mode of the file that was used`
to create the file object through the open() function.

closed :This attribute is True if the file is closed.

File_att.py

f = open("a.txt", "r")
print ("Name of the file:", f.name)
print ("Opening mode:", f.mode)
print ("Closed? :", f.closed)
f.close()
print ("Closed? :", f.closed)

write a python script to open a text file , store data into file from
key board, read data from that file and display
file3.py
f = open('text.txt', 'a')
print("Enter text data into file 'end ' to stop")
while True :
st=input()
if(st=='end'):
break
f.write(st+'\n')

f.close()

f = open('text.txt','r')
lines = f.read()
print (lines)
f.close()

sleep
It is Method belongs time module, it delays flow of execution up to
Specified no of seconds.

sleep(seconds)

write a python script to enter any file name and display all
content in the given file

file4.py
import time
name=input("Enter any file name :");
f = open(name,'r')
while True :
ch = f.read(1)
if len(ch) ==0 :
break
print (ch,end='')
time.sleep(.10)
f.close()
Example program for seek method :
File5.py
f = open('h.txt', 'a+')
print("Enter text data into file 'end ' to stop")
while True :
st=input()
if(st=='end'):
break
f.write(st+'\n')
f.seek(0,0)
print("\nReading data from file")
lines = f.read()
print (lines)
f.close()

Copying contents from one File to another

filecopy.py
f1 = open('a.txt', 'r')
lines = f1.read()
f1.close()
f2 = open('b.txt', 'w' )
f2.write(lines)
f2.close()
print("Fileis copied successfully")
print("Copied contents in the second file");
f2 = open('b.txt', 'r' )
lines = f2.read()
print (lines)
f2.close()

Deleting Content from a File


(delete 2nd and 3rd line of a file)
delfilecontent.py

f = open('a.txt','r')
lines = f.readlines()
print('Original content of the file:')
for ln in lines:
print(ln,end='')
f.close()
del lines[1:3]
f = open('a.txt', 'w' )
f.writelines(lines)
f.close()
print('\nThe content of the file after deleting second and third line:')
f = open('a.txt', 'r' )
lines = f.read()
print (lines)
f.close()

Binary File Operations

Storing text data into binary file

Python String ‘encode’ and ‘decode’ methos

encode: It encodes the string with specified ‘code’


str.encode( code)

decode: It decodes the string with specified ‘code’


str.decode( code)

codes : utf-8,ascii,etc.

utf-8 : utf stands for Unicode Transformation Format. The '8' means it uses 8-bit
blocks to represent a character.

binaryfile1.py
st = 'welcome to Python Binary files'
f = open("h.bin","wb" )
f.write(st.encode('utf-8'))
f.close()
f = open("h.bin","rb" )
fcontent=f.read()
f.close()
print('The content in the file ')
print (fcontent.decode('utf-8'))

Serialization (Pickling)
Serialization (also known as pickling) is a process of converting
structured (list, tuple, class, etc.) data into data stream format.
Serialization is done when storing data, and deserialization is done when
retrieving data. For pickling, you can use the module ‘pickle’ .

dump(obj, file)
This method belongs to pickle module, and is used to Write object
to a file.

load(file)
This method belongs to pickle module, and is used to read object
from a file.

bfile1.py
import pickle
class num:
def __init__(self, x):
self.n = x

def display(self):
print("Given Number :", self.n)

ob=num(100)
f = open('num.bin', 'wb')
pickle.dump(ob, f)
f.close()
del ob
f = open('num.bin','rb')
obj = pickle.load(f)
obj.display()

bfile2.py
import pickle
class student:
def datainput(self) :
self.id = int(input("Enter Student Id :"))
self.name = input("Enter Student Name :")
self.emailadd=input("Enter Email Eddress :")
def display(self):
print("Student ID:", self.id)
print("Studentr Name:", self.name)
print('Email Address:', self.emailadd)

f = open("stu.bin", "wb")
ob=student()
while True:
ob.datainput()
pickle.dump(ob,f)
ch=input("Do you wanto to Continue(y/n) :")
if ch=='n' or ch=='N' :
break
f.close()
print('\nInformation of the Students')
f = open("stu.bin","rb")
while True:
try :
obj = pickle.load(f)
except EOFError:
break
else:
obj.display()
print()
f.close()
Exception Handling
Exception is an error state, it occurs during the execution of an
instruction in a program. when an exception occurs it is possible to raise an
exception and when an exception is raised a set of instructions will be
executed and these instructions are referred as exception handler. When
an exception occurs, Python usually displays a technical message.
Syntax errors are different from exceptions, if syntax errors occur when
any statement doesn’t match the grammar of the Python interpreter.

To handle exceptions, you write the code in a block that begins with the
word try. There are two kinds of try blocks
1) try/except
2) try/finally

try/except:
The code written in the try block, and all the exceptions are handled
through the except clause. If you specify exception type, the except clause
can handle a single specified exception. If you don’t specify any exception,
except will handle all exceptions that appear in the code written in the try
block.

Syntax:
try:
statement(s)
except [SomeException]:
code for handling exception
[else:
statement(s)]

Some Exceptions That Can Be Handled While Running a Program

Exception Description
1. EOFError : Raised when you try to read beyond the
end of a file.
2. FloatingPointError : Raised when a floating-point operation
fails.
3. IOError : Raised when an I/O operation fails.
4. IndexError : Raised when you use an index value that is
out of range.

5. TypeError : Raised when an argument of inappropriate


type is supplied.
6. ValueError : Raised when an inappropriate argument
value is supplied.
7. ZeroDivisionError : Raised when a number is divided by 0

Etc.

Exp1.py
try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
c=a/b
print("Division :",c);
except ZeroDivisionError:
print ('Division Error' )

exp2.py
import sys
try:
name = input('Enter your name : ')
print ('Given name :', name)
except :
print ('EOF error has occurred' )

exp3.py

m = input('Enter First number : ')


if m.isdigit():
m=int(m)

n = input('Enter Second number : ')


if n.isdigit():
n=int(n)

try:
d=m/n
print ('Division :',round(d,2))
except TypeError:
print ('You have not entered a numeric value")
except ZeroDivisionError:
print ('You have entered zero value, Division is Not possible")

Nested try
exp33.py
m = input('Enter First number : ')
n = input('Enter Second number : ')
try :
m=int(m)
n=int(n)

try:
d=m/n
print ('Division :',round(d,2))
except ZeroDivisionError:
print ("You have entered zero value, Division is Not possible")

except :
print ("You have not entered numeric values")

try/finally:
The code written in the finally block always executes whether an
exception occurs or not.
exp4.py
try:
f = open("a.txt", "r")
try:
lines = f.read()
print (lines)
finally:
f.close()
except IOError:
print ('File does not exist')

Raising an Exception
Exceptions are automatically raised when some undesired situation occurs
during program execution. You can raise an exception explicitly through
the ‘raise’ statement in a ‘ try/except ‘ block.

Syntax:
raise ExceptionType

exp5.py
try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
if b==0 :
raise ZeroDivisionError
c=a/b
print("Division :",round(c,2));
except ZeroDivisionError:
print ('Division Error' )

User defined Exceptions


Although Python’s build in exceptions handle most common errors. We
want to create our own exception type to handle situation to our
application. This is quite easy to do, just define a sub class of Exception .

exp6.py
class myException(Exception):
def __init__(self,st):
self.mesg = st

def getmessage(self):
return self.mesg

try:
print("Enter any two Numbers ")
a=int(input())
b=int(input())
if b==0 :
raise myException("Division Error")
c=a/b
print("Division :",round(c,2))
except EOFError:
print ('You pressed EOF ')
except myException as me:
print (me.getmessage())
else:
print ('No Exceptions')

The Python Standard Library


Built-in Functions
abs , bin , bool , chr, dict , dir , eval , float , format, help , hex , input, int
, len , list , min , oct , ord , print , sorted , str , sum , complex , range
reversed , round , set, tuple, type ,etc.

abs(x) :
Return the absolute value of a number.
bin(x) :
Convert an integer number to a binary string prefixed with “0b”.

hex(x) :
Convert an integer number to a lowercase hexadecimal string
prefixed with “0x”.
oct(x) :
Convert an integer number to an octal string prefixed with “0o”.

num_sys.py
n=int(input("Enter any Number :"))
print("Absolute value of given Number :",abs(n))
print("Binary value of given Number :",bin(n))
print("Octal value of given Number :",oct(n))
print("Hexadecimal value of given Number :",hex(n))

Eg:
Conversion binary,oct and hexdecimal to integer.
int('0b100',2) = 4
int('0o644',8) = 420
int ('0x1a4',16)=420

help
It displays help content of specified object.
Syntax:
help(object)

eg:
>>> help(str)

Turtle graphics
Turtle graphics is a popular for introducing programming to kids. It was
part of the original Logo programming language. Imagine a robotic turtle
starting at (0, 0) in the x-y plane.
turtle:
The turtle module is an extended reimplementation of Python standard
distribution up to version Python 2.5.

Turtle methods
Move and draw
forward() | fd()
backward() | bk() | back()
right() | rt()
left() | lt()
goto() | setpos() | setposition()
home()
circle()
setx()`
sety()
screensize() | setup()
Tell Turtle’s state
position() | pos()
xcor()
ycor()
Color control
color()
pencolor()
fillcolor()
Filling
begin_fill()
end_fill()
Turtle state Visibility
showturtle() | st()
hideturtle() | ht()

etc.

tg1.py
from turtle import *
for i in range(4):
forward(50)
right(90)

tg2.py
from turtle import *
for i in range(5):
forward(200)
right(144)

done()

tg3.py
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()

tg4.py

from turtle import *


pencolor("blue")
for i in range(100):
forward(200)
left(123)
if i==50:
pencolor("red")

done()

Python - GUI Programming


Python provides various options for developing graphical user
interface applications. Most important are Tkinter , JPython , PyQt,etc.

Tkinter Programming
Tkinter is the standard GUI library for Python. Tkinter provides a fast and
easy way to create GUI applications.

Steps for Creating a GUI application using Tkinter


· Import the tkinter module.

· Create the GUI application main window.

· Add one or more widgets to the GUI application.

· Enter the main event loop.

Tk()

It creates a toplevel (main) window of an application.

geometry()

It sets tkinter window size

Syntax:

geometry("Width x Height")

eg: geometry("300x200")

title()

It sets window title

Syn:

title(str)

mainloop()

It Runs the main event loop


Eg:

gui1.py
import tkinter
top = tkinter.Tk()
top.title("Python GUI");
top.geometry ("300x100")
top.mainloop()

Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes
used in a GUI application. These controls are commonly called widgets.

1.Button :

The Button widget is used to add buttons in a Python GUI application.


These buttons can display text or images. You can attach a function or a
method to a button which is called automatically when you click the button.

Syntax

Button ( master, option=value, ... )

Parameters
· master − It represents the parent window.

· options − Here is the list of most commonly used options for


this widget..

Options :
text : display text on the Button

command : Function or method to be called when the button

is clicked.

font,image,height,width,etc.

pack()

It Packs(Display) a widget in the parent window.

messagebox

It is a class belongs to 'tkinter'

showinfo():

It is a class method belongs to messagebox class,It Displays a message


on a separate window

syntax:

showinfo(windowtitle,message)

gui2.py

from tkinter import *

top = Tk()

top.geometry("300x100")
def func():

messagebox.showinfo( "PYTHON GUI", "WELCOME TO GUI


PROGRAMMING")

B = Button(top, text ="CLICK", command = func)

B.pack()

top.mainloop()

2.Canvas
The Canvas is a rectangular area for drawing pictures or other layouts.
You can place text, widgets or frames on a Canvas.

Syntax:

Canvas ( master, option=value, ... )

Parameters

master − This represents the parent window.

options − Here is the list of most commonly used options for this widget.

options:

bg : Normal background color.

width,height,etc.

The Canvas widget can be Used to Display Image


image − Creates an image item, which can be an instance of either the
BitmapImage or the PhotoImage classes.

fileobject=PhotoImage(file = "image.gif")

canvas.create_image(width, Height, image=fileobject)

gui3.py

import tkinter

top = tkinter.Tk()

C = tkinter.Canvas(top, height=400, width=600)

filename =tkinter.PhotoImage(file = "image.gif")

C.create_image(300, 200, image=filename)

C.pack()

top.mainloop()

3.Checkbutton

The Checkbutton widget is used to display a number of options to a user


as toggle buttons.

Syntax

Checkbutton ( master, option, ... )

options: width,height,onvalue,offvalue,etc.
gui4.py

from tkinter import *

top = Tk()

C1 = Checkbutton(top, text = "Music", onvalue = 1, offvalue = 0,

height=5,width = 20)

C2 = Checkbutton(top, text = "Video", onvalue = 1, offvalue = 0,

height=5,width = 20)

C1.pack()

C2.pack()

top.mainloop()

4.Label
This widget implements a display box where you can place text or images.

Syntax

Label ( master, option, ... )

5. Entry

The Entry widget is used to accept single-line text string.

Syntax
Entry( master, option, ... )

Gui5.py

from tkinter import *

top = Tk()

L = Label(top, text="User Name")

L.pack( side = LEFT)

E = Entry(top)

E.pack(side = RIGHT)

top.mainloop()

6.Frame

The Frame widget is very important for the process of grouping and
organizing other widgets . It works like a container, which is responsible
for arranging the position of other widgets.

Syntax

Frame ( master, option, ... )

Gui6.py
from tkinter import *

root = Tk()

frame = Frame(root)

frame.pack()

bottomframe = Frame(root)

bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")

redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")

greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")

bluebutton.pack( side = LEFT )

blackbutton = Button(bottomframe, text="Black", fg="black")

blackbutton.pack( side = BOTTOM)

root.mainloop()

7.Listbox

The Listbox widget is used to display a list of items from which a user can
select items.

syntax
Listbox ( master, option, ... )

insert :

It is method belongs to Listbox and is used to insert items at specified


index.

insert(index,item)

gui7.py

from tkinter import *

top = Tk()

Lb1 = Listbox(top)

Lb1.insert(0, "Python")

Lb1.insert(1,"C")

Lb1.insert(2,"C++")

Lb1.insert(3,"Java")

Lb1.pack()

top.mainloop()

8.Menu

This widget is used to create all kinds(pop-up, pull-


down,etc.) of menus that can be used by our applications.
Syntax

Menu ( master, option, ... )

Methods

These methods are available on Menu objects

add_command (options) :

Adds a menu item to the menu.

options :label,command,etc.

add_cascade(options):

It Displays menus on Menubar.

add_separator() :

Adds a separator line to the menu.

config()

This Method belongs to gui window and it configures


and displays menu bar on window.

Gui8.py
from tkinter import *

def donothing():

messagebox.showinfo("GUI","WELCOME TO PYTHON
MENUS")

root = Tk()

menubar = Menu(root)

filemenu = Menu(menubar,tearoff=0)

filemenu.add_command(label="New",
command=donothing)

filemenu.add_command(label="Open",
command=donothing)

filemenu.add_command(label="Save",
command=donothing)

filemenu.add_command(label="Save as...",
command=donothing)
filemenu.add_command(label="Close",
command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit",
command=root.quit)

menubar.add_cascade(label="File", menu=filemenu)

editmenu = Menu(menubar, tearoff=0)

editmenu.add_command(label="Undo",
command=donothing)

editmenu.add_separator()

editmenu.add_command(label="Cut",
command=donothing)
editmenu.add_command(label="Copy",
command=donothing)

editmenu.add_command(label="Paste",
command=donothing)

editmenu.add_command(label="Delete",
command=donothing)

editmenu.add_command(label="Select All",
command=donothing)

menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu = Menu(menubar, tearoff=0)

helpmenu.add_command(label="Help Index",
command=donothing)

helpmenu.add_command(label="About...",
command=donothing)

menubar.add_cascade(label="Help", menu=helpmenu)
root.config(menu=menubar)

root.mainloop()

9.Toplevel

The Toplevel widget is used to provide a separate


window container

Syntax

Toplevel ( option, ... )

Gui9.py
from tkinter import *

top = Tk()

top.geometry("300x100")

def func():

ob=Toplevel()

ob.title("MYWINDOW")

B = Button(top, text ="New Window", command = func)


B.pack()

top.mainloop()

Database Handling
Sometimes you need to save data entered by the user for
future use. There are two ways to save data that is supplied by the
user while running an application. The first way is to use file
handling. The second way is to use a database management
system.
To interface with a database using Python, you need the Python
database API, which supports a wide range of database servers,
such as MySQL, Microsoft SQL Server , Oracle , Etc. You need to
download a separate database API module for each database you
want to access. Here we want to access MySQL Database Server
through Python.

Why MySQL?
MySQL is one of the most popular relational database management
systems . It’s open-source software, secure, fast, and very easy to
learn.

For accessing MySQL Database Server through Python, you need


to download and install the pymysql/MySQLdb module.
Note:
Before proceeding with installing the pymysql/MySQLdb module,
make sure that MySQL database server is installed on your
computer. You can download the current version from the following
URL: http://dev.mysql.com/downloads/.
pymysql/MySQLdb
pymysql/MySQLdb is an interface for connecting Python code to
a MySQL database server. You can insert, fetch, delete, and update
database tables by writing simple SQL statements and executing
through Python code.

MYSQL COMMANDS-1
1.Create a database on the mysql server :
create database database_name ;

2.List all databases on the mysql server :


show databases;

3.Switch to a database :
use database_name ;

connect:
It is a method belongs to pymysql/MYSQLdb module and it
connects the mysql database server and returns connection object.
Syntax:
connect(host, user, passwd, db)

close:
It is a method belongs to connection object and it closes the
database connection.
Syntax:
connection_object.close()

db1.py

import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
print("Connected to Database")
except :
print("Unable to Commect database")
conn.close()

MYSQL COMMANDS-2

1.Create table :

Syntax:
Create table table_name (columnName-1 datatype,…….,columnName-n datatype);
Eg:
create table emp (eno int,ename char(20), salary float);

2.To see all the tables in the database:


show tables;

3.To see table field formats:


desc table_name;

4.To delete a database:


drop database database_name;

5. To Delete a table :
drop table table_name;

6. To display rows in the table


select * from table_name;

cursor()
This Method belongs to connection object ,it creates a cursor object.
Using this cursor object we can execute sql statements.
execute():
this Methos Belongs to cursor object and it executes sql statements;
syntax:
cusorobject. execute(sql statement)

db2.py
import pymysql
try:
conn=pymysql.connect (host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
cursor.execute (''' create table emp (eno int,ename char(20), salary float) ''')
print("Table is Created")
cursor.close()
conn.close()
except :
print ("Unable to create Table")

Inserting Rows in a Database Table:

insert into table_name values(value-1,..,value-n);

eg:
insert into emp values(100,'abc',5000.00)

commit():
This method belongs to connection object.To apply the modifications to
the database table, use the commit() method.
Once commit() is executed, then it’s not possible to undo the changes.

Db3.py
import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
cursor.execute (''' insert into emp(eno,ename,salary)
values (200, 'xyz', 25000.00) ''')
print("One Row Inserted")
cursor.close()
conn.commit()
conn.close()
except :
print ("Unable to insert Row")

rollback():
The rollback() method cancels all the modifications applied to the
database table. It keeps the database table when it was last saved.

db4.py

import pymysql
try:
conn=pymysql.connect(host="localhost",user="root",passwd="harshith",db="mydb")
cursor=conn.cursor()
while True:
eno=int(input("Enter Eno :"))
ename=input("Enter Ename :")
salary=float(input("Enter Salary :"))
try:
cursor.execute (''' insert into emp(eno,ename,salary) values (%d, '%s', %f) '''
%(eno,ename,salary))
print("One Row Inserted")
conn.commit()
except:
conn.rollback()
ch=input("do you want to insert Another Record (y/n) :")
if ch=='n' or ch=='N' :
break;
cursor.close()
conn.close()
except :
print ("Unable to insert Row")

Fetching Rows from the Table


fetchone():
This method belongs to cusor object and it fetches one row in resultset.
fetchall():
This method belongs to cusor object and it fetches all the rows in resultset.
db5.py
import pymysql
try:

conn=pymysql.connect(host="localhost",user="root",passwd="hars
hith",db="mydb")
cursor=conn.cursor()
try:
cursor.execute ("SELECT * from emp")
print ("ENO\t\tENAME\t\tSALARY")
print("----------------------------------------------------------")
while(1):
row=cursor.fetchone()
if row==None:
break
print ("%d\t\t%s\t\t%.2f" %(row[0], row[1], row[2]))
except :
print ("Error in fetching rows")
cursor.close()
conn.close()
except :
print ("Unable to connect database")

db6.py

import pymysql
try:

conn=pymysql.connect(host="localhost",user="root",passwd="harshith",d
b="mydb")
cursor=conn.cursor()
try:
cursor.execute ("select * from emp")
print("----------------------------------------------------------")
print ("ENO\t\tENAME\t\tSALARY")
print("----------------------------------------------------------")
rows=cursor.fetchall()
for row in rows:
print("%d\t\t%s\t\t%.2f" %(row[0], row[1], row[2]))

except :
print ("Error in fetching rows")
print("----------------------------------------------------------")
cursor.close()
conn.close()
except :
print ("Unable to connect database")

Potrebbero piacerti anche