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

Problem Solving & Python Programming Manual

Uploaded by

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

Problem Solving & Python Programming Manual

Uploaded by

arunram1912
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

St.

PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

GE3171 - PROBLEM SOLVING AND PYTHON


PROGRAMMING LABORATORY
(REGULATION 2021)
YEAR /SEMESTER : I/I

LAB MANUAL
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054
INSTRUCTIONS TO STUDENTS
 Before entering the lab the student should carry the following things
(MANDATORY)
1. Identity card issued by the college.
2. Class notes
3. Lab observation book
4. Lab Manual
5. Lab Record
 Student must sign in and sign out in the register provided when attending the
lab sessionwithout fail.
 Come to the laboratory in time. Students, who are late more than 15 min.,
will not beallowed to attend the lab.
 Students need to maintain 100% attendance in lab if not a strict action will be
taken.
 All students must follow a Dress Code while in the laboratory
 Foods, drinks are NOT allowed.
 All bags must be left at the indicated place.
 Refer to the lab staff if you need any help in using the lab.
 Respect the laboratory and its other users.
 Workspace must be kept clean and tidy after experiment is completed.
 Read the Manual carefully before coming to the laboratory and be sure
about what youare supposed to do.
 Do the experiments as per the instructions given in the manual.
 Copy all the programs to observation which are taught in class before
attending the labsession.
 Students are not supposed to use floppy disks, pen drives without
permission of lab- incharge.
 Lab records need to be submitted on or before the date of submission.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

VISION

To emerge as an Institution of Excellence by providing High Quality Education in


Engineering, Technology and Management to contribute for the economic as well as
societal growth of our Nation.

MISSION

 To impart strong fundamental and Value-Based Academic knowledge in various


Engineering, Technology and Management disciplines to nurture creativity.
 To promote innovative Research and Development activities by collaborating with
Industries, R&D organizations and other statutory bodies.
 To provide conducive learning environment and training so as to empower the students
withdynamic skill development for employability.
 To foster Entrepreneurial spirit amongst the students for making a positive impact on
remarkable community development.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


VISION

 To empower our students to take part in progressive socio– economic conditioned nation
building process by creating diligent, adept and responsible Computer Science Engineers.

MISSION
 To provide Quality Engineering Education through cutting edge technologies in
Computer Science and Engineering.
 To provide conducive learning milieu to comprehend nitty-gritty of computing process,
edify the students to become successful professional lifelong learners.
 To establish Industry-Institution liaison to make the students to cater the needs of
Industry.
 To promote projects and activities in the promising areas of Engineering and Technology.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

PROGRAM EDUCATIONAL OBJECTIVES

Program Educational Objectives describe the career and professional accomplishments in


five years after the graduation that the program is preparing graduates to achieve.

 PEO1: Apply their technical competence in computer science to solve real world
problems, with technical and people leadership.

 PEO2: Conduct cutting edge research and develop solutions on problems of social
relevance.

 PEO3: Work in a business environment, exhibiting team skills, work ethics, adaptability
and lifelong learning.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

COURSE OUTCOME

On completion of the course, students will be able to:

CO1: Develop algorithmic solutions to simple computational problems

CO2: Develop and execute simple Python programs.

CO3: Implement programs in Python using conditionals and loops for solving problems.

CO4: Deploy functions to decompose a Python program.

CO5: Process compound data using Python data structures.


St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

PROGRAM OUTCOME

Program Outcome describe the knowledge, skills and attitudes the students should acquires at the
end of a four years of engineering program

PO-1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO-2. Problem analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO-3. Design/ development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO-4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO-5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO-6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

PO-7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

PO-8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO-9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

PO-10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO-11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO-12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

PROGRAM SPECIFIC OUTCOMES

Program Specific Outcomes are statements that describe what the graduates of a specific
engineering program should be able to do

PSO-1: Exhibit design and programming skills to build and automate business solutions using
cutting edge technologies.

PSO-2 : Strong theoretical foundation leading to excellence and excitement towards research, to
provide elegant solutions to complex problems.

PSO-3 : Ability to work effectively with various engineering fields as a team to design, build and
develop system applications.
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

Mapping Matrix – Course Vs PEOs

Course PEO-1 PEO-2 PEO-3 PEO-4 PEO-5

GE3171/PROBLEM SOLVING AND 2 3 3 - -


PYTHON PROGRAMMING
Mapping Matrix – Mission Vs PEOs

Mission PEO-1 PEO-2 PEO-3 PEO-4 PEO-5

M1 3 3 2 - -
M2 2 2 3 - -
M3 1 1 2 - -
M4 3 3 3 - -
M5 - - - - -

1: Low 2: Moderate (Medium) 3: Substantial (High) No correlation, put “-”

Mapping Matrix – PEOs Vs POs/ PSOs

Pos PSOs
PEOs
PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PO- PSO- PSO- PSO-
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3

PEO1 3 3 3 3 2 2 2 3 3 3 2 1 3 3 1
PEO2 1 1 2 2 3 2 3 3 2 2 2 3 1 1 3
PEO3 1 1 1 1 1 1 1 1 3 3 3 3 3 3 3
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

Mapping Matrix – COs Vs POs/ PSOs

POs PSOs
CO
s PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
-1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -1 -2 -3

CO
2 1 3 2 - - - - - - 2 2 3 3 -
-1

CO
3 3 3 3 2 - - - - - 2 2 3 - -
-2

CO
2 2 - - 2 - - - - - 1 - 3 - -
-3

CO
1 2 - - 1 - - - - - 1 - 2 - -
-4

CO
2 2 - - 2 - - - - - 1 2 2 3 -
-5
GE3171 - PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY
SYLLABUS

1. Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same. (Electricity Billing, Retail shop billing, Sin series,
weight of a motorbike, Weight of a steel bar, compute Electrical Current in Three
Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of
two variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns, pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –
operations of list & tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of
shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas,
numpy. Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by
zero error, voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc
CONTENTS
Week Name of the program PgNo

Identification and solving of simple real life or scientific or technical


1
problems, and developing flow charts for the same. (Electricity
Billing, Retail shop billing, Sin series, weight of a motorbike, Weight
Python programming using simple statements and expressions (exchange
2 the values of two variables, circulate the values of n variables, distance
between two points).

3 Scientific problems using Conditionals and Iterative loops. (Number


series, Number Patterns, pyramid pattern)

Implementing real-time/technical applications using Lists, Tuples. (Items


4 present in a library/Components of a car/ Materials required for construction
of a building –operations of list & tuples)
Implementing real-time/technical applications using Sets,
5 Dictionaries. (Language, components of an automobile, Elements of a
civil structure, etc.- operations of Sets & Dictionaries)

6 Implementing programs using Functions. (Factorial, largest number in


a list, area of shape)

7 Implementing programs using Strings. (reverse, palindrome, character


count, replacing characters)

8 Implementing programs using written modules and Python Standard


Libraries (pandas, numpy. Matplotlib, scipy)

9 Implementing real-time/technical applications using File handling.


(copy from one file to another, word count, longest word)

Implementing real-time/technical applications using Exception


10 handling. (divide by zero error, voter’s age validity, student mark
range validation)
11 Exploring Pygame tool.

Developing a game activity using Pygame like bouncing ball, car race etc
12
CONTENT BEYOND SYLLABUS
Script mode of python
13
Looping & Switching statements using tuples
14
User defined functions
15
ELECTRICITY BILLING

AIM :
To write a python program to execute an electricity billing .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read units
STEP 3 : If units < 50 , amounts = units*2.60 & surcharge = 25
STEP 3.1 : Elseif units <= 100 , amount = 130+162.50+((units – 100)*5.26) &
surcharge = 25
STEP 3.2 : Else amount = 130+162.50+526+((units – 200)*8.45) & surcharge = 75
STEP 4 : Total = amount + surcharge
STEP 5 : Print total
STEP 6 : Stop

PROGRAM:
units=int(input("ENTER THE NUMBER OF UNITS CONSUMED:"))
if units<50:
amount=units*2.60
surcharge=25
elif units<=100:
amount=130+162.50+((units-100)*5.26)
surcharge=45
else:
amount=130+162.50+526+((units-200)*8.45)
surcharge=75
total=amount+surcharge
print("\nELECTRICITY BILL=%.2f" %total)

1
OUTPUT:
ENTER THE NUMBER OF UNITS CONSUMED:100
ELECTRICITY BILL=337.50
>>>

RESULT :
Hence , the python program to execute an electricity billing is executed successfully and the
output is obtained .

2
RETAIL SHOP BILLING

AIM :
To write a python program to perform a retail shop billing .

ALGORITHM :
STEP 1 : Start
STEP 2 : Create lists product_name , product_quantity , product_price
STEP 3 : Get inputs from the user
STEP 4 : Display the output
STEP 5 : Stop

PROGRAM:
product_name=[]
product_quantity=[]
product_price=[]
company_name='STUDENT STORE'
company_address='xxx'
company_city='yyy'
message='THANKS FOR SHOPPING.PLEASE COME AGAIN'
for i in range(3):
product_name.append(input("ENTER THE NAME OF THE PRODUCT:"))
product_quantity.append(int(input("ENTER THE QUANTITY OF THE PRODUCT:")))
product_price.append(int(input("ENTER THE PRICE OF THE PRODUCT:")))
print("\n\t\t####BILL####")
print('*'*50)
print("\t\t{}".format(company_name.title()))
print("\t\t{}".format(company_address.title()))
print("\t\t{}".format(company_city.title()))
print('*'*50)

3
print('\tPRODUCT NAME\tQUANTITY\tPRICE')
print('-'*50)
i=0
for i in range(3):
print("\t",product_name[i],"\t",product_quantity[i],"\t",product_price[i])
print('='*50)
print('\t\t\tTOTAL')
total=0
i=0
for i in range(3):
total+=(product_price[i]*product_quantity[i])
print('\t\t\tRS.{}'.format(total))
print('='*50)
print('\n\t{}\n'.format(message))
print('*'*50)

OUTPUT:
ENTER THE NAME OF THE PRODUCT:pen
ENTER THE QUANTITY OF THE PRODUCT:20
ENTER THE PRICE OF THE PRODUCT:20
ENTER THE NAME OF THE PRODUCT:pencil
ENTER THE QUANTITY OF THE PRODUCT:10
ENTER THE PRICE OF THE PRODUCT:10
ENTER THE NAME OF THE PRODUCT:eraser

4
ENTER THE QUANTITY OF THE PRODUCT:10
ENTER THE PRICE OF THE PRODUCT:5

####BILL####
**************************************************
Student Store
Xxx
Yyy
**************************************************
PRODUCT NAME QUANTITY PRICE

pen 20 20
pencil 10 10
eraser 10 5
TOTAL
RS.400
RS.500
RS.550

THANKS FOR SHOPPING.PLEASE COME AGAIN

**************************************************

RESULT :
Hence , the python program to perform a retail shop billing is executed successfully and the
output is obtained .

5
SINE SERIES

AIM :
To write a python program to perform a sine series .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read inputs from the user
STEP 3 : Import math
STEP 4 : Define sin(X,N)
STEP 5 : Call sin and display it arguments
STEP 6 : Stop

PROGRAM:
X=int(input("ENTER THE VALUE IN DEGREE:"))
N=int(input("ENTER THE NUMBER OF TERMS:"))
import math
def sin(X,N):
sine=0
for i in range(N):
sign=(-1)**i
pi=22/7
y=X*(pi/180)
sine=sine+((y**(2.0*i+1))/math.factorial(2*i+1))*sign
return sine
print(round(sin(X,N),2))

OUTPUT:
ENTER THE VALUE IN DEGREE:30
ENTER THE NUMBER OF TERMS:2

6
0.5

RESULT :
Hence , the python program to perform the sin series is executed successfully and the output
is obtained .

7
WEIGHT OF A MOTORBIKE

AIM :
To write a python program to display weight of motorbikes .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read input ‘a’ from the user
STEP 3 : According to the type of bike given as input , display the weight of the bike using
if…elif…else statements
STEP 4 : Stop

PROGRAM:
a=input("ENTER THE TYPE OF
MOTORCYCLE(sport,chopper,adventure,dirt,touring,bagger,cruiser,racer,scooter,moped):")
if a=="chopper":
print("WEIGHT OF THE MOTORBIKE:315 kg")
elif a=="adventure":
print("WEIGHT OF THE MOTORBIKE:250 kg")
elif a=="dirt":
print("WEIGHT OF THE MOTORBIKE:100 kg")
elif a=="touring":
print("WEIGHT OF THE MOTORBIKE:400 kg")
elif a=="sport":
print("WEIGHT OF THE MOTORBIKE:180 kg")
elif a=="bagger":
print("WEIGHT OF THE MOTORBIKE:340 kg")
elif a=="cruiser":
print("WEIGHT OF THE MOTORBIKE:250 kg")
elif a=="racer":
print("WEIGHT OF THE MOTORBIKE:200 kg")

8
elif a=="scooter":
print("WEIGHT OF THE MOTORBIKE:115 kg")
elif a=="moped":
print("WEIGHT OF THE MOTORBIKE:80 kg")

OUTPUT:
ENTER THE TYPE OF
MOTORCYCLE(sport,chopper,adventure,dirt,touring,bagger,cruiser,racer,scooter,moped):sp
ort
WEIGHT OF THE MOTORBIKE:180 kg
>>>

RESULT :
Hence , the python program to display the weight of the motorbike is executed successfully
and the output is obtained .

9
WEIGHT OF A STEEL BAR
AIM :
To write a python program to display the weight of a steel bar.

ALGORITHM :
STEP 1 : Start
STEP 2 : Read the input d & l
STEP 3 : Define the function weight
STEP 4 : Display the weight of the steel bar
STEP 5 : Stop

PROGRAM:
d=int(input("ENTER THE DIAMETER OF THE STEEL BAR:"))
l=int(input("ENTER THE LENGTH OF THE STEEL BAR:"))
x=162
def weight(d,x):
weight=0
for i in range(d,x):
weight=((d**2)*(l)/x)
return weight
print("WEIGHT OF THE STEEL BAR:",weight(d,x))

OUTPUT:
ENTER THE DIAMETER OF THE STEEL BAR:50
ENTER THE LENGTH OF THE STEEL BAR:30
WEIGHT OF THE STEEL BAR: 462.962962962963
>>>

10
RESULT :
Hence , the python program to display the weight of the steel bar is executed successfully and
the output is obtained .

11
COMPUTE ELECTRICAL CURRENT IN THREE
PHASE CIRCUIT

AIM :
To write a python program to compute the electrical current in three phase circuit .

ALGORITHM :
STEP 1 : Start
STEP 2 : Import math module
STEP 3 : Read the inputs
STEP 4 : Calculate the current in the three phase circuit
STEP 5 : Print the values
STEP 6 : Stop

PROGRAM:
from math import sqrt,cos
import cmath
r_ph=16
x_l=12
v_l=int(input("ENTER THE LINE VOLTAGE:"))
f=50
v_ph=v_l/sqrt(3)
z_ph=r_ph+1j*x_l
i_ph=v_ph/z_ph
i_l=i_ph
phi=cmath.phase(i_l)
cosphi=r_ph/abs(z_ph)
p=sqrt(3)*v_l*abs(i_l)*cosphi
print("THE LINE VOLTAGE IS:",v_l)
print("THE PHASE VOLTAGE IS:",round(v_ph,2))

12
print("THE LINE CURRENT IN A IS:",round(abs(i_l),2))
print("POWER FACTOR IS :",cosphi,"LAGGING")
print("THE POWER ABSORBED IN W IS:",p)

OUTPUT:
ENTER THE LINE VOLTAGE:200
THE LINE VOLTAGE IS: 200
THE PHASE VOLTAGE IS: 115.47
THE LINE CURRENT IN A IS: 5.77
POWER FACTOR IS : 0.8 LAGGING
THE POWER ABSORBED IN W IS: 1600.0000000000002
>>>

RESULT :
Hence , the python program to calculate the electrical current of the three phase circuit is
executed successfully and the output is obtained .

13
EXCHANGE THE VALUE OF TWO VARIABLES

AIM :
To write a python program to exchange the value of two variables .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read X & Y from user
STEP 3 : Swap X & Y using temp
STEP 4 : Return X & Y
STEP 5 : Stop

PROGRAM:
X=int(input('ENTER A NUMBER:'))
Y=int(input('ENTER A NUMBER:'))
temp=X
X=Y
Y=temp
print("THE VALUE OF X AFTER SWAPPING:{}".format(X))
print("THE VALUE OF Y AFTER SWAPPING:{}".format(Y))
OUTPUT:
ENTER A NUMBER:2
ENTER A NUMBER:3
THE VALUE OF X AFTER SWAPPING:3
THE VALUE OF Y AFTER SWAPPING:2
>>>

14
RESULT :
Hence , the python program to exchange the value of two variables is executed successfully
and the output is obtained .

15
CIRCULATE THE VALUE OF N VARIABLES

AIM :
To write a python program to calculate the value of N variables .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read the values
STEP 3 : Return the values
STEP 4 : Stop

PROGRAM:
no_of_terms=int(input("ENTER NUMBER OF VALUES:"))
list1=[]
for val in range(0,no_of_terms,1):
ele=int(input("ENTER INTEGER:"))
list1.append(ele)

OUTPUT:
ENTER NUMBER OF VALUES:3
ENTER INTEGER:2
ENTER INTEGER:7
ENTER INTEGER:5

RESULT :
Hence , the python program to calculate the value of N variables is executed successfully
and the output is obtained .

16
DISTANCE BETWEEN TWO POINTS

AIM :
To write a python program to find the distance between two points .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read x1 , x2 , y1 ,y2 from the user
STEP 3 : Calculate distance = ((x1-x2)**2+(y1-y2)**2)**0.5
STEP 4 : Return distance
STEP 5 : Stop

PROGRAM:
x1=int(input("ENTER THE VALUE X1:"))
y1=int(input("ENYER THE VALUE Y1:"))
x2=int(input("ENTER THE VALUE X2:"))
y2=int(input("ENTER THE VALUE Y2:"))
distance=((x1-x2)**2+(y1-y2)**2)**0.5
print("DISTANCE BETWEEN THE POINTS ({},{}) AND ({},{}) IS
{}".format(x1,y1,x2,y2,distance))

OUTPUT:
ENTER THE VALUE X1:1
ENYER THE VALUE Y1:2
ENTER THE VALUE X2:3
ENTER THE VALUE Y2:4
DISTANCE BETWEEN THE POINTS (1,2) AND (3,4) IS 2.8284271247461903

17
RESULT :
Hence , the python program to find the distance between two points is executed successfully
and the output is obtained .

18
NUMBER SERIES

AIM :
To write a python program to display the number series .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read ‘n’ from the user
STEP 3 : Display the number series upto ‘n’ using for loop
STEP 4 : Stop

PROGRAM:
n=int(input("ENTER A NUMBER:"))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if i<n:
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()

OUTPUT:
ENTER A NUMBER:5
1 + 2 + 3 + 4 + 5 = 15

RESULT :
Hence , the python program to display the number series is executed successfully and the
output is obtained .

19
NUMBER PATTERN

AIM :
To write a python program to display a number pattern .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read ‘n’ from the user
STEP 3 : Display the number pattern using for loop
STEP 4 : Stop

PROGRAM:
n=int(input("ENTER THE NUMBER:"))
for i in range(n//2,n,2):
for j in range(1,n-i,2):
print(" ",end="")
for j in range(i):
print(j+1,end="")
for j in range(1,n-i,1):
print(" ",end="")
for j in range(i):
print(j+1,end="")
print()
for i in range(n,0,-1):
for j in range(i,n):
print(" ",end="")
for j in range(i*2):
print(j+1,end="")
print()

20
OUTPUT:
ENTER THE NUMBER : 4
12345678
123456
1234
12
>>>

RESULT :
Hence , the python program to display a number pattern is executed successfully and the
output is obtained .

21
PYRAMID PATTERN

AIM :
To write a python program to display a pyramid pattern .

ALGORITHM :
STEP 1 : Start
STEP 2 : Read ‘n’ from the user
STEP 3 : Display the pyramid pattern using for loop
STEP 4 : Stop

PROGRAM:
n=int(input("ENTER THE NUMBER OF ROWS:"))
for i in range(1,n+1):
print(' '*(n-i)+'* '*i)

OUTPUT:
ENTER THE NUMBER OF ROWS:5
*
**
***
****
*****
>>>

RESULT :
Hence , the python program to display a pyramid pattern is executed successfully and the
output is obtained .

22
ITEMS IN A LIBRARY

AIM :
To write a python program to access items in a library .

ALGORITHM :
STEP 1 : Start
STEP 2 : Create a list ‘lib’
STEP 3 : Access the elements of lib using methods like sort , pop , extend ,len ,append ,clear
,count,insert ,index .
STEP 4 : Display the outputs
STEP 5 : Stop

PROGRAM:
lib=[]
print(lib)
lib=["python","c","thirukural","wings of fire"]
print(lib)
lib.append(["datastructure","cse"])
lib.extend(["AI","TOC"])
print(lib)
lib.insert(1,'engineering maths')
print(lib)
lib=["python","c","thirukural","wings of fire","tenaliraman","java the complete
reference","HTML"]
del lib[5]
print(lib)
lib.remove('c')
print(lib)
a=lib.pop(1)
print('POPPED ELEMENT:',a,'LISTREMAINING:',lib)

23
lib.clear()
print(lib)
lib=["python","c","thirukural","wings of fire","tenaliraman","java the complete
reference","HTML"]
for book in lib:
print(book)
print(lib)
print(lib[3])
print(lib[0:2])
print(lib[::-1])
lib=["python","c","thirukural","wings of fire","tenaliraman","java the complete
reference","HTML"]
print(len(lib))
print(lib.index("c"))
print(lib.count("c"))
print(sorted(lib))
lib.sort(reverse=1)
print(lib)

OUTPUT:
[]
['python', 'c', 'thirukural', 'wings of fire']
['python', 'c', 'thirukural', 'wings of fire', ['datastructure', 'cse'], 'AI', 'TOC']
['python', 'engineering maths', 'c', 'thirukural', 'wings of fire', ['datastructure', 'cse'], 'AI',
'TOC']
['python', 'c', 'thirukural', 'wings of fire', 'tenaliraman', 'HTML']
['python', 'thirukural', 'wings of fire', 'tenaliraman', 'HTML']
POPPED ELEMENT: thirukural LIST REMAINING: ['python', 'wings of fire', 'tenaliraman',
'HTML']
[]
python
c

24
thirukural
wings of fire
tenaliraman
java the complete reference
HTML
['python', 'c', 'thirukural', 'wings of fire', 'tenaliraman', 'java the complete reference', 'HTML']
wings of fire
['python', 'c']
['HTML', 'java the complete reference', 'tenaliraman', 'wings of fire', 'thirukural', 'c', 'python']
7
1
1
['HTML', 'c', 'java the complete reference', 'python', 'tenaliraman', 'thirukural', 'wings of fire']
['wings of fire', 'thirukural', 'tenaliraman', 'python', 'java the complete reference', 'c', 'HTML']
>>>

RESULT :
Hence , the python program to access items in a library is executed successfully and the
output is obtained .

25
COMPONENTS OF A CAR
PROGRAM:
c=("CARNAME","COLOUR","NOOFSEAT","FUEL TYPE")
lc=["GEAR","STEERING","WHEEL","DOOR"]
comp=tuple(lc)
print(c)
print(lc)
print(comp)
print(comp[1:])

OUTPUT:
('CARNAME', 'COLOUR', 'NOOFSEAT', 'FUEL TYPE')
['GEAR', 'STEERING', 'WHEEL', 'DOOR']
('GEAR', 'STEERING', 'WHEEL', 'DOOR')
('STEERING', 'WHEEL', 'DOOR')
>>>

26
MATERIALS REQUIRED FOR THE CONSTRUCTION OF A BUILDING
PROGRAM:
construction_item=["CEMENT","CONCRETE MOTOR","SAND","BRICKS","WATER"]
print('RESULT FOR THE BUILDING CONSTRUCTION MATERIALS ARE AS
FOLLOWS:\n')
for index,construction_item in enumerate(construction_item):
items=str(index+1)
print('sno:'+items+'\nitems:'+construction_item.title())

OUTPUT:
sno:1
items:Cement
sno:2
items:Concrete Motor
sno:3
items:Sand
sno:4
items:Bricks
sno:5
items:Water
>>>

27
LANGUAGE
PROGRAM:
language={'lang#1':'machine lang','lang#2':'assembly lang','lang#3':'high level lang'}
language['high level lang']='python'
print(language)
python=language.copy()
language_sorted=language.items()
print("DISPLAY ALL LANGUAGE:",python)
print("DISPLAY ALL LANGUAGE:",language.items())
print("DISPLAY ALL LANGUAGE:",language_sorted)

OUTPUT:
{'lang#1': 'machine lang', 'lang#2': 'assembly lang', 'lang#3': 'high level lang', 'high level lang':
'python'}
DISPLAY ALL LANGUAGE: {'lang#1': 'machine lang', 'lang#2': 'assembly lang', 'lang#3':
'high level lang', 'high level lang': 'python'}
DISPLAY ALL LANGUAGE: dict_items([('lang#1', 'machine lang'), ('lang#2', 'assembly
lang'), ('lang#3', 'high level lang'), ('high level lang', 'python')])
DISPLAY ALL LANGUAGE: dict_items([('lang#1', 'machine lang'), ('lang#2', 'assembly
lang'), ('lang#3', 'high level lang'), ('high level lang', 'python')])
>>>

28
COMPONENTS OF AN AUTOMOBILE
PROGRAM:
automobile={1:'ENGINE',2:'BATTERY',3:'RADIATOR',4:'BRAKES'}
automobile[5]='STEERING'
print(automobile)
for key in automobile.keys():
print(key,end='')
for key in automobile.values():
print(key,end='')
del automobile[5]
print(automobile)

OUTPUT:
{1: 'ENGINE', 2: 'BATTERY', 3: 'RADIATOR', 4: 'BRAKES', 5: 'STEERING'}
12345ENGINEBATTERYRADIATORBRAKESSTEERING{1: 'ENGINE', 2: 'BATTERY',
3: 'RADIATOR', 4: 'BRAKES'}
>>>

29
ELEMENTS OF A CIVIL STRUCTURE
PROGRAM:
civil_structure={1:'BEAM',2:'STRUTS',3:'TIES',4:'TIE RODS'}
civil_structure[5]='EYE BARS'
civil_structure[5]='WIRES'
print(civil_structure)
for key,value in civil_structure.items():
print(key,value)
civil_structure.update({3:'WIRE ROPES'})
print(civil_structure)
civil_structure1={1:'SUSPENSION CABLES',2:'ROPES'}
dic_merged={**civil_structure,**civil_structure1}
print(dic_merged)

OUTPUT:
{1: 'BEAM', 2: 'STRUTS', 3: 'TIES', 4: 'TIE RODS', 5: 'WIRES'}
1 BEAM
2 STRUTS
3 TIES
4 TIE RODS
5 WIRES
{1: 'BEAM', 2: 'STRUTS', 3: 'WIRE ROPES', 4: 'TIE RODS', 5: 'WIRES'}
{1: 'SUSPENSION CABLES', 2: 'ROPES', 3: 'WIRE ROPES', 4: 'TIE RODS', 5: 'WIRES'}
>>>

30
FRACTIONALS
PROGRAM:
from fractions import Fraction
a=int(input("ENTER THE NUMERATOR:"))
b=int(input("ENTER THE DENOMINATOR:"))
print(“THE FRACTIONAL NUMBER IS:”,Fraction(a,b))

OUTPUT:
ENTER THE NUMERATOR:2
ENTER THE DENOMINATOR:3
THE FRACTIONAL NUMBER IS: 2/3
>>>

31
LARGEST NUMBER IN A LIST
PROGRAM:
a=[]
n=int(input("ENTER THE NUMBER OF ELEMENTS:"))
for i in range(n):
list=int(input("ENTER THE ELEMENT IN THE LIST:"))
a.append(list)
a.sort()
maximum=0
if list>maximum:
maximum=list
print("MAXIMUM ELEMENT IN THE LIST:",list)

OUTPUT:
ENTER THE NUMBER OF ELEMENTS:5
ENTER THE ELEMENT IN THE LIST:1
ENTER THE ELEMENT IN THE LIST:2
ENTER THE ELEMENT IN THE LIST:3
ENTER THE ELEMENT IN THE LIST:4
ENTER THE ELEMENT IN THE LIST:5
MAXIMUM ELEMENT IN THE LIST: 5
>>>

32
AREA OF A SHAPE
PROGRAM:
a=input("ENTER THE NAME OF THE SHAPE:")
if a=="rectangle":
l=int(input("ENTER THE LENGTH OF THE RECTANGLE:"))
b=int(input("ENTER THE BREADTH OF THE RECTANGLE:"))
area=l*b
print("AREA OF THE RECTANGLE:",area)
elif a=="square":
c=int(input("ENTER THE SIDE OF THE SQUARE:"))
area=c**2
print("AREA OF THE SQUARE:",area)
elif a=="triangle":
d=int(input("ENTER THE BASE OF THE TRIANGLE:"))
e=int(input("ENTER THE HEIGHT OF THE TRIANGLE:"))
area=0.5*d*e
print("AREA OF THE TRIANGLE:",area)
elif a=="circle":
f=int(input("ENTER THE RADIUS OF THE CIRCLE:"))
area=3.14*(f**2)
print("AREA OF CIRCLE:",area)
else:
print("INVALID SHAPE,PLEASE TRY AGAIN")

33
OUTPUT:
ENTER THE NAME OF THE SHAPE:rectangle
ENTER THE LENGTH OF THE RECTANGLE:5
ENTER THE BREADTH OF THE RECTANGLE:3
AREA OF THE RECTANGLE: 15

ENTER THE NAME OF THE SHAPE:square


ENTER THE SIDE OF THE SQUARE:2
AREA OF THE SQUARE: 4

ENTER THE NAME OF THE SHAPE:triangle


ENTER THE BASE OF THE TRIANGLE:6
ENTER THE HEIGHT OF THE TRIANGLE:3
AREA OF THE TRIANGLE:9.0

ENTER THE NAME OF THE SHAPE:circle


ENTER THE RADIUS OF THE CIRCLE:7
AREA OF CIRCLE: 153.86

34
REVERSE STRING

PROGRAM:
def myfunction(x):
return x[::-1]
mytxt=myfunction(input("ENTER YOUR SENTENCE:"))
print(mytxt)

OUTPUT:
ENTER YOUR SENTENCE:you are what you build
dliubuoytahw era uoy

35
PALINDROME
PROGRAM:
num=int(input("ENTER THE NUMBER:"))
a=num
sum=0
rnum=0
while num!=0:
rem=int(num)%10
sum=sum+rem
rnum=(rnum*10)+rem
num=int(num)//10
print("THE SUM OF THE DIGITS OF",a,"IS:",sum)
print("THE REVERSE NUMBER OF THE ",a,"IS:",rnum)
if a==rnum:
print("THE GIVEN NUMBER IS PALINDROME")
else:
print("THE GIVEN NOT A PALINDROME")

OUTPUT:
ENTER THE NUMBER:454
THE SUM OF THE DIGITS OF 454 IS: 13
THE REVERSE NUMBER OF THE 454 IS: 454
THE GIVEN NUMBER IS PALINDROME
>>>

36
CHARACTER COUNT
PROGRAM:
from collections import Counter
mystring=input("ENTER YOUR SENTENCE:")
counter=Counter(mystring)
print(counter)

OUTPUT:
ENTER YOUR SENTENCE:you are the best version of yourself
Counter({' ': 6, 'e': 5, 'o': 4, 'r': 3, 's': 3, 'y': 2, 'u': 2, 't': 2, 'f': 2, 'a': 1, 'h': 1, 'b': 1, 'v': 1, 'i': 1, 'n':
1, 'l': 1})
>>>

37
REPLACING CHARACTERS
PROGRAM:
txt=input("ENTER YOUR SENTENCE:")
n=input("ENTER THE WORD YOU WANT TO REPLACE:")
s=input("ENTER THE WORD TO BE REPLACED:")
x=txt.replace(n,s)
print(x)

OUTPUT:
ENTER YOUR SENTENCE:you are the best version of yourself
ENTER THE WORD YOU WANT TO REPLACE:best
ENTER THE WORD TO BE REPLACED:worst
you are the worst version of yourself
>>>

38
PANDAS
PROGRAM:
import pandas as pd
data={“CALORIES”:[420,380,390],”DURATION”:[50,40,45]}
df=pd.DataFrame(data)
print(df)

OUTPUT:
CALORIES
DURATION

420

50
1 380 40
2 390 45

39
NUMPY
PROGRAM:
import numpy as np
array1=np.array([[1,2,3],[4,5,6]])
array2=np.array([[7,8,9],[10,11,12]])
print(array1+array2)
print(“-“*20)
print(array1-array2)
print(“-“*20)
print(array1*array2)
print(“-“*20)
print(array2/array1)
print(“-“*40)
print(array1**array2)
print(“-“*40)
OUTPUT:
[[8 10 12]
[14 16 18]]_ _ _ _ _ _ _ _ _ _

[[-6 -6 -6]
[-6 -6 -6]]_ _ _ _ _ _ _ _ _ _

[[7 16 27]
[40 55 72]]_ _ _ _ _ _ _ _ _ _

[[7. 4. 3. ]
[2.5 2.2 2. ]]_ _ _ _ _ _ _ _ _ _

[[1 256 19683]


[1048576 48828125 2118184960]]_ _ _ _ _ _ _ _ _ _ _

40
MATPLOTLIB
PROGRAM:
import matplotlib.py plot as plt
days=[1,2,3,4,5]
slices=[2,2,2,13]
activites=[‘sleeping’,’eating’,’working’,’playing’]
cols=[‘c’,’m’,’r’,’b’]
plt.pie(slices,labels=activities,colours=cols,startangle=180)
plt.title(‘PIE PLOT”)
plt.s
how()

OUTPUT:

41
SCIPY
PROGRAM:
from scipy import constants
print(constants.yotta)
print(constants.zetta)
print(constants.exa)
print(constants.peta)
print(constants.tera)
print(constants.giga)
print(constants.mega)
print(constants.kilo)
print(constants.hecto)
print(constants.deka)
print(constants.deci)
print(constants.centi)
print(constants.milli)
print(constants.micro)
print(constants.pico)
print(constants.nano)
print(constants.femto)
print(constants.atto)
print(constants.zepto)

OUTPUT:
1e+24
1e+21
1e+18
1000000000000000.0
1000000000000.0
1000000000.0

42
1000000.0
1000.0
100.0
10.0
0.1
0.01
0.001
1e-06
1e-09
1e-12
1e-15
1e-18
1e-21

43
COPY FROM ONE FILE TO ANOTHER
PROGRAM:
source=input(“ENTER SOURCE FILE NAME”)
dest=input(“ENTER DEST FILE NAME”)
source=open(“source.txt”,”r”)
dest=open(“dest.txt”,”w”)
for I in source:
dest.write(i)
source.close()
dest.close()
print(“FILE COPIED SUCCESSFULLY”)
print(“CONTENTS OF DEST FILE”)
fn=open(“dest.txt”,”r”)
print(fn.read())
fn.close()
OUTPUT:
ENTER SOURCE FILE NAME source.txt
ENTER DEST FILE NAME dest.txt
FILE COPIED SUCCESSFULLY
CONTENTS OF DEST FILE

44
WORD COUNT
PROGRAM:
a_string=input("ENTER YOUR SENTENCE:")
word_list=a_string.split()
number_of_words=len(word_list)
print("NUMBER OF WORDS IN YOUR SENTENCE IS:",number_of_words)

OUTPUT:
ENTER YOUR SENTENCE:you are what you build
NUMBER OF WORDS IN YOUR SENTENCE IS: 5
>>>

45
LONGEST WORD
PROGRAM:
def largestword(s):
s=sorted(s,key=len)
print(s[-1])
if name ==" main ":
s=input("ENTER YOUR SENTENCE:")
l=list(s.split(" "))
largestword(l)

OUTPUT:
ENTER YOUR SENTENCE: you are what you build
Build
>>>

46
DIVIDE BY ZERO ERROR
PROGRAM:
try:
a=int(input("ENTER THE FIRST NUMBER:"))
b=int(input("ENTER THE SECOND NUMBER:"))
result=a/b
print(result)
except valueerror as e:
print("INVALID INPUT.PLEASE INPUT INTEGER")
except zerodivisionerror as e:
print(e)

OUTPUT:
ENTER THE FIRST NUMBER:3
ENTER THE SECOND NUMBER:23
0.13043478260869565
>>>

47
VOTER’S AGE VALIDATION
PROGRAM:
age=int(input("ENTER YOUR AGE:"))
if age>=18:
status="ELLIGIBLE"
else:
status="NOT ELLIGIBLE"
print("YOU ARE ",status,"TO VOTE.")

OUTPUT:
ENTER YOUR AGE:21
YOU ARE ELLIGIBLE TO VOTE.
>>>

48
STUDENT MARK RANGE VALIDATION
PROGRAM:
a=input("ENTER THE NAME OF THE STUDENT:")
b=int(input("ENTER YOUR REGISTRATION NUMBER:"))
if a=="xxx":
b=="1234"
print("YOUR MARKS IS 98/100")
print("PASS")
elif a=="yyy":
b=="4567"
print("YOUR MARKS IS 99/100")
print("PASS")
elif a=="zzz":
b=="7890"
print("YOUR MARKS IS 80/100")
print("PASS")
elif a=="sss":
b=="1357"
print("YOUR MARKS IS 43/100")
print("FAIL")
else :
print(“ INVALID INPUT")

OUTPUT:
ENTER THE NAME OF THE STUDENT:xxx
ENTER YOUR REGISTRATION NUMBER:1234
YOUR MARKS IS 98/100
PASS
>>>

49
PYGAME TOOL
PROGRAM:
import pygame
import math
import sys
pygame.init()
screen=pygame.display.setmode((600,300))
pygame.display.setcaption(“ELLIPTICAL ORBIT”)
clock=pygame.time.Clock()
while (true):
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
xradius=250
yradius=100
for degree in range(0,360,10):
x1=int(math.cos(degree*2*math.pi/360)*xradius)+300
y1=int(math.sin(degree*2*math.pi/360)*yradius)+150
screen.fill((255,255,255))
pygame.draw.circle(screen,(255,0,0),[300,150],35)
pygame.draw.ellipse(screen,(200,125,0),[50,50,500,200],1)
pygame.draw.circle(screen,(0,0,255),[x1,y1],15)
pygamw.display.flip()
clock.tick(5)

50
OUTPUT:

51
BOUNCING BALL
PROGRAM:
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT']="hide"
import sys,pygame
from pygame.locals import*
pygame.init()
speed=[1,1]
colour=(255,250,250)
width=550
height=300
screen=pygame.display.set_mode((width,height))
pygame.display.set_caption("Pygame bouncing ball")
ball=pygame.image.load("ball.png")
rect_boundry=ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry=rect_boundry.move(speed)
if rect_boundry.left<0 or rect_boundry.right>width:
speed[0]=-speed[0]
if rect_boundry.top<0 or rect_boundry.bottom>height:
speed[1]=-speed[1]
screen.fill(colour)
screen.blit(ball,rect_boundry)
pygame.display.flip()
if event.type==QUIT:
pygame.quit()
sys.exit

52
OUTPUT:

53
St. PETER'S
COLLEGE OF ENGINEERING & TECHNOLOGY
Affiliated to Anna University | Approved by AICTE | ISO 9001:2015 Certified | NAAC with ‘A’ Grade
Avadi, Chennai, Tamilnadu – 600 054

PYTHON LAB SAMPLE EXERCISES PROBLEMS

PYTHON SHELL :
There are 2 modes in every version of python shell . They are INTERACTIVE and SCRIPT
MODE .

 INTERACTIVE MODE –
 When you open python shell , the interactive mode will be default for you to
code on .
 In interactive mode , the output of your written code will be displayed directly
in the same page , at the next line .
 The inputs are limited to one line , i.e , once one line of code is coded and
when you press the enter key , the single code is compiled and the output is
given at the next line .
 The interactive mode is compiled line by line and the output is given after
each line , i.e , it is compile time .

 SCRIPT MODE –
 When you open a new page in the python shell itself , the script mode will be
opened .
 In script mode , we have to type our entire code and save the file with “.py”
extension and run the program .
 The output and errors will appear in a new page .
 The script mode is compiled the whole , i.e , entire program is coded and then
compiled .
 It is run time .

[ For our lab we are going to use script mode only . To use script mode you first open python
shell and open a new tab by choosing “new file” in the “FILE” option in the menu bar .]

1
INPUT AND OUTPUT COMMANDS :
 INPUT –
o In python , we can give input to the code by directly assigning a value to a variable .
o Basics of TOKENS you would have learnt in theory classes .
o We can get user inputs during output process by using “input()” keyword .
o You can specify the data type of input that is to be acquired by the user to restrict the
inputs to that specified type.
 OUTPUT –
o The output is displayed using the “print()” statement .
EXAMPLE :
a = 10 {direct assigning}
b = int(input(“ENTER A NUMBER :”)) {user input}
[In input statement , we specify the datatype be declaring them restraining “input()” statement
within it.
For integer type inputs - int()
For float type inputs - float()
For character inputs - we just use input() , it is default
To display text or sentences in the output screen while getting user inputs , we type the content
between “” within input() statement ]
c=a+b
name = input(“ENTER YOUR NAME :”)
print(“Your name is “ , name)
print(“1 st Year A Section”)
print(“Sum of 10 and “ , b , “is :” , c)
[In print statement , we can print any statement we need by constraining the content within “”
inside the print() statement .
To display the value of a variable , we just type the variable name within the print() statement.
For both context and variable value to be displayed in the output , we type the content within
“” and type the variable name followed by a comma “,” .]

Program without explanation :


a = 10
b = int(input(“ENTER A NUMBER :”))
c=a+b

2
name = input(“ENTER YOUR NAME :”)
print(“Your name is “ , name)
print(“1 st Year A Section”)
print(“Sum of 10 and “ , b , “is :” , c)

OUTPUT –
ENTER A NUMBER : 5
ENTER YOUR NAME : PYTHON
Your name is PYTHON
1 st Year A Section
Sum of 10 and 5 is 15
 Try your own sample programs using I\O Statements.
CONDITIONAL STATEMENTS :
 The conditional statements in python are the statements which are used as conditions
to determine if a certain set of code is to be executed or not .
 In simple terms , these are statements that is used to control the flow of a program.
 The basic conditional statement we use in python is IF….ELSE statement .
 First a set of code is written under if statement with a condition and then the alternate
set of code is written under else statement .
 The flow is first passed to the if statement , where the given condition is checked . If
the given condition is satisfied , then the lines of code indented within it is executed .
 If the “if” statement condition is not satisfied , then the flow passes to the else
statement and the lines of code indented within it is executed .

EXAMPLE :
n = int(input(“ENTER A NUMBER :”))
if n % 2 = = 0 :
print(“Your number is even”)
else :
print(“Your number is odd”)
[ Here we first get an user input of a number , then in the if statement we give a condition to
check if the modulus of user given number is equal to 0 or not , if the condition results as true
then the print() statement within it will get executed and the program ends without going to
else statement . If the given condition is false for the given user input , then the print statement
under the else statement is executed and the program ends .

3
NOTE : The code under both IF and ELSE statements are to be given with and
indent(space{use tab key}) or else and indentation error will rise.]

OUTPUT –
ENTER A NUMBER : 27
Your number is odd
 Try your own programs using if…else statements
LOOPING STATEMENTS :
The looping statements are a set code written within a condition and is executed repeatedly
until the condition is satisfied .
FOR LOOP –
The for loop is a looping statement that uses a given range within which the given set of
codes are iterated and executed .
EXAMPLE :
f = int(input(“ENTER THE NUMBER TO FIND FACTORIAL OF :”))
fact = 1
if f > 0 :
print(“Invalid”)
elif f == 0 :
print(“The factorial is 0”)
else :
for i in range(1 , f + 1) :
fact *= i
print(“The factorial of “ , f , “ is :” , fact)
[Here , we get the input from the user first and we assign “fact” is equal to 0 . Then we check if
f is lesser than 0 and if so print() statement under if statement is printed . If the IF Statement is
not true then the elif statement is checked…..’note that the elif statement is also an if statement
except that every additional conditions to be checked after an if statement is given with elif as
keyword and there can be as many elif statements between if and else statements as
required’….. If the elif statement is true then the print() statement under it is executed . If not
satisfied then the flow moves to the else statement , where for each value of “i” within the range
of 1 and f + 1 , i.e , the range starts from 1 and keeps on executing the set codes under for loop
until the previous value of the end value {( end -1 )th value} , where each iteration with
incremented value of “i” within the given range the “fact” is (fact * i) = fact , i.e , the fact is
multiplied by “i” and the result is overwrote to fact . The fact is printed after all iteration is
complete .]

4
OUTPUT :
ENTER THE NUMBER TO FIND FACTORIAL OF : 3
The factorial of 3 is : 6

 Try your own program using for loop statement

WHILE LOOP –
The while loop is a looping statement that executes a set of codes repeatedly until a condition
is satisfied .

EXAMPLE :
n = int(input(“Upto what number do u want the Fibonacci series ? “))
a=0
b=1
count = 0
f=0
print(“Fibonacci sequence :”)
while count < n :
print(a)
f=a+b
a=b
b = f
count += 1
[Fibonacci series concept :
First term is 0 and the second term is 1 and the series goes on with the
third term is equal to the sum of 1st term and 2nd term ( 3rd term = 1st term + 2nd term) .
Then the first term is swapped with the second term and the second term
is swapped with the third term , i.e , 1st term = 2nd term and 2nd term = 3rd term]

5
OUTPUT :
Upto what number do u want the Fibonacci series ? 7
Fibonacci sequence :
0
1
1
2
3
5
8

 Try your own program using while loop statement

USER DEFINED FUNCTIONS :


The user defined functions are the definition functions coded by the user , which can be
accessed whenever called in the program .
You can define function with a set of code which u can access anywhere throughout the
program as many time as required simply by calling it .
EXAMPLE –
def sqr_no() :
n = int(input(“Enter a number :”))
sqr = n**2
print(“The square of “ , n “is :” , sqr)
sqr_no()

[Here , we define a function “sqr_no” with no arguments and write down the square of a
number program code . After completing the definition part we call the function “sqr_no” and
the program is executed]
OUTPUT –
Enter a number : 4
The square of 4 is : 16
 Try your own program using definition functions

6
TRY YOURSELF :
 Write a python program to get your name and print it.
 Write a python program to print the statement “ A Section” 5 times using for loop.
 Write a python program to get a number from the user and check if it is prime or not a prime
number using if else statements.
 Write a python program to sum up all the numbers upto the user given number using while
loop .
 Write a python program using user defined functions to calculate the cube of a given number.
 Write a python program to perform a simple calculator of operations ( + , - , * , \ ) with the
operator and numbers are user inputs .

You might also like