0% found this document useful (0 votes)
4 views23 pages

Python Programming

The document provides a comprehensive guide to Python programming, covering various topics such as simple programs, decision-making, loops, lists, functions, and charts. It includes example codes for calculating areas, checking even/odd numbers, and drawing charts, among others. Each section contains practical exercises to reinforce learning and understanding of Python concepts.

Uploaded by

Shakeel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views23 pages

Python Programming

The document provides a comprehensive guide to Python programming, covering various topics such as simple programs, decision-making, loops, lists, functions, and charts. It includes example codes for calculating areas, checking even/odd numbers, and drawing charts, among others. Each section contains practical exercises to reinforce learning and understanding of Python concepts.

Uploaded by

Shakeel
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Simple Programs
Decision Making Programs - If and if elif related programs
Loops related programs
List related programs
Function related programs
Charts related programs
Pre-Board Practical Paper and Model Paper Programs
File Handling
Error Handling
Simple Programs (Top)

Write a program that calculates area of a rectangle.

l = float(input("Enter length "))


w = float(input("Enter Width "))
a = l*w
print("Area = ",a)

Write a program that inputs mass and velocity from user and calculates kinetic
energy.

m = float(input("Enter Mass "))


v = float(input("Enter Velocity "))
ke = 1/2*m*v*v
print("Kinetic Energy = ",ke)
OR
m = float(input("Enter Mass "))
v = float(input("Enter Velocity "))
ke = 1/2*m*v**2
print("Kinetic Energy = ",ke)
Write a program calculates are of a circle using formula:
Area = πr2

r = float(input("Enter Radius of a circle "))


a = 3.1416*r**2
print("Area of circle is ",a)

Write a program that input a number and calculate its cube.

n = int(input("Enter a number "))


res = n**3
print("Cube = ", res)

Write a program that inputs a number and an exponent from user and calculate
power of that number. .

n = int(input("Enter a number "))


e = int(input("Enter Exponent "))
res = n**e
print("Power of the number is ", res)

Write a program that calculates 30 percent of a number entered by user.

n = float(input("Enter a number "))


res = 30/100*n
print("30 percent of ",n," is ",res)

Write a program that calculates net pay from basic pay using following criteria:
House rent is 10 percent of basic pay
Transport Allowance is 5 percent of basic pay
Medical Allowance is 15 percent of basic pay
Income Tax is 7% of basic pay

bp = float(input("Enter Basic Pay "))


hr = 10/100*bp
ta = 5/100*bp
ma = 15/100*bp
it = 7/100*bp
np = bp+hr+ta+ma-it
print("Net Pay =" ,np)
Decision Making Programs (Top)

Write a program that inputs a number and decide whether it is even or odd.

n = int(input("Enter a number "))


r = n%2
if r == 0:
print("Number is Even ")
else:
print("Number is Odd ")

Using if

n = int(input("Enter a number "))


r = n%2
if r == 0:
print("Number is Even ")
if r!= 0:
print("Number is Odd ")

Write a program that inputs a number and check if it is multiple of 7 or not.

n = int(input("Enter a number "))


r = n%7
if r == 0:
print("Number is Multiple of 7 ")
else:
print("Number is Not Multiple of 7 ")

Using if

n = int(input("Enter a number "))


r = n%7
if r == 0:
print("Number is Multiple of 7 ")
if r != 0:
print("Number is Not Multiple of 7 ")
Write a program that inputs a number and decides whether a number is
negative or non-negative.

n = float(input("Enter a number "))


if n < 0:
print("Number is negative ")
else:
print("Number is non-negative ")

Write a program that inputs percentage from user and calculate grade using
following criteria.
90 and above A1
80-90 A
70-80 B
60-70 C
50-60 D
40-50 E
Below 40 F
Using if elif

per = float(input("Enter percentage: "))

if per >= 90:


print("Grade = A1")
elif per >= 80:
print("Grade = A")
elif per >= 70:
print("Grade = B")
elif per >= 60:
print("Grade = C")
elif per >= 50:
print("Grade = D")
elif per >= 40:
print("Grade = E")
else:
print("Grade = F")
Using if

per = float(input("Enter percentage: "))

if per >= 90:


print("Grade = A1")

if per >= 80 and per < 90:


print("Grade = A")

if per >= 70 and per < 80:


print("Grade = B")

if per >= 60 and per < 70:


print("Grade = C")

if per >= 50 and per < 60:


print("Grade = D")

if per >= 40 and per < 50:


print("Grade = E")

if per < 40:


print("Grade = F")

Write a program that gets sides of triangle from user and checks if the triangle
is Equilateral, Isosceles or scalene.
Equilateral Triangle: All sides are equal
Isosceles Triangle: Any two sides equal
Scalene Triangle: No side is equal

Using if elif
a = float(input("Enter first side: "))
b = float(input("Enter second side: "))
c = float(input("Enter third side: "))

if a == b and b == c:
print("Equilateral Triangle")

elif (a == b or b== c or a == c):


print("Isosceles Triangle")
else:
print("Scalene Triangle")

Using If

a = float(input("Enter first side: "))


b = float(input("Enter second side: "))
c = float(input("Enter third side: "))

if a == b and b == c:
print("Equilateral Triangle")

if (a == b and a != c) or (a == c and a!=b) or (b==c and b!= a):


print("Isosceles Triangle")

if a != b and b != c and a != c:
print("Scalene Triangle")

Write a program that inputs three number and find largest number.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if num1 >= num2 and num1 >= num3:


largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

print("Largest number is:", largest)


Loops Related Programs (Top)

Write a program that prints odd numbers from 1 to 100.

for i in range(1, 100, 2):


print(i)

using while

i=1
while i <= 100:
print(i)
i = i+2

Write a program that prints reverse odd numbers from 100 to 1.

for i in range(99,0,-2):
print(i)

using while

i = 99
while i >= 1:
print(i)
i = i-2
Write a program that prints numbers and their squares from 1 to 10.

for i in range(1,11,1):
print(i, i*i)
OR
for i in range(1,11,1):
sq = i*i
print(i, sq)
using while
i=1
while i<= 10:
print(i,i*i)
i = i+1
OR
i=1
while i<= 10:
sq = i*i
print(i,sq)
i = i+1

Write a program that inputs a number and prints its table.

n = int(input("Enter a number "))


for i in range(1,11,1):
print(n,"*",i,"=",n*i)

Using while

n = int(input("Enter a number "))


i=1
while i<= 10:
print(n,"*",i,"=",n*i)
i = i+1

Write a program that calculates sum of numbers from 1 to 10.

s= 0
for i in range(1,11,1):
s = s+i

print("Sum of numbers ",s)

using while
s= 0
i=1
while i <= 10:
s = s+i
i=i+1
print("Sum of numbers ",s)
Write a program that calculates sum of square of numbers from 1 to 10.

s= 0
for i in range(1,11,1):
s = s+i*i

print("Sum of square of numbers ",s)

using while

s= 0
i=1
while i <= 10:
s = s+i*i
i = i+1

print("Sum of square of numbers ",s)

Write a program that calculates product of numbers from 1 to 10.

p= 1
for i in range(1,11,1):
p = p*i

print("Product of numbers ",p)

using while

p= 1
i=1
while i <= 10:
p = p*i
i=i+1

print("Product of numbers ",p)


Write a program that inputs a number and print its factorial.

n = int(input("Enter a number "))


f=1
for i in range(1,n+1,1):
f = f*i

print("Factorial of the number is ",f)

using while

n = int(input("Enter a number "))


i=1
f=1
while i <= n:
f = f*i
i = i+1

print("Factorial of the number is ",f)

List Related Programs (Top)

Write a program stores 10 marks in a list and print list.

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
print(marks)

Write a program stores 10 marks in a list and print minimum and maximum.

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
print("Minimum Marks ",min(marks))
print("Maximum Marks ",max(marks))

Write a program stores 10 marks in a list and find a number entered by user.

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
n = int(input("Enter a number "))
if n in marks:
print("Number is in list ")
else:
print("Number is not in the list ")
Write a program stores 10 marks in a list and find how many times a specific
number appears in a list. The number will be provided by user.

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
n = int(input("Enter a number "))
print([Link](n))

Write a program stores 10 marks in a list and print list using loop.

Method 1 - Using variable i as index

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
for i in range(0,10,1):
print(marks[i])

Method 2 - Using variable i as List value

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
for i in marks:
print(i)

Method 3 – Using while loop

marks = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
i=0
while(i<=9):
print(marks[i])
i=i+1

Write a program that prints elements of list but skipping those numbers that
are multiple of 6.

num = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
s=0
for i in range(0,10,1):
if(num[i]%6 != 0):
print(num[i])
Write a program that prints elements of list using loop but skipping those
numbers that are multiple of 6 using continue statement.

num = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
s=0
for i in range(0,10,1):
if(num[i]%6 == 0):
continue
print(num[i])

Write a program that prints sum and average of list 10 elements using sum
function.

num = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
s = sum(num)
avg = s/10
print("Sum of list ", s)
print("Average of List ",avg)

Write a program that prints sum and average of list 10 elements using loop.

Method 1: Using i as index

num = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
s=0
for i in range(0,10,1):
s = s + num[i]

avg = s/10
print("Sum of list ", s)
print("Average of List ",avg)

Method 2: Using i as list value

num = [12, 45, 78, 95, 34, 27, 8, 88, 78, 62]
s=0
for i in num:
s=s+i
avg = s/10
print("Sum of list ", s)
print("Average of List ",avg)
Function Related Programs (Top)

Write a program that uses function to calculate square a number entered by


user.

def square(num):
return num**2

n = int(input("Enter a number "))


print(square(n))

Write a program that uses function calculate sum of two numbers entered by
user.

Method 1
def sum(x,y):
z = x+y
return z

n1 = int(input("Enter first number "))


n2 = int(input("Enter second number "))
s = sum(n1,n2)
print("Sum = ",s)

Method 2
def sum(x,y):
return x+y

n1 = int(input("Enter first number "))


n2 = int(input("Enter second number "))
print("Sum = ",sum(n1,n2))

Write a program that uses function to calculate area of rectangle.

def area(l,w):
a = l*w
return a
length = float(input("Enter Length "))
width = float(input("Enter Width "))
ar = area(length, width)
print("Area = ", ar)
Write a program that uses function to calculate factorial of a number entered
by user.

def factorial(num):
f=1
for i in range(1, num+1, 1):
f =f*i
return f

n = int(input("Enter a number "))


fact = factorial(n)
print("Factorial = ", fact)

Write a program that uses function to print table of a number entered by user.

def table(num):
for i in range(1, 11, 1):
print(num,"*",i,"=",num*i)

n = int(input("Enter a number "))


table(n)

Charts Related Programs (Top)

Write a program that draws line chart for following equation. y = 3x+4

import numpy as n
import [Link] as p
x = [Link](0, 11,1)
y=3*x+4
[Link](x,y)
[Link]("Line Chart (y = 3x + 4)")
[Link]("x")
[Link]("y")
[Link](True)
[Link]()
Write a program that draws dots (scatter) representation for following
equation. y = 3x+4

import numpy as n
import [Link] as p
x = [Link](0, 11,1)
y=3*x+4
[Link](x,y)
[Link]("Scatter Chart (y = 3x + 4)")
[Link]("x")
[Link]("y")
[Link](True)
[Link]()

Write a program that draws bar chart for following equation. y = 3x+4

import numpy as n
import [Link] as p
x = [Link](0, 11,1)
y=3*x+4
[Link](x,y)
[Link]("Scatter Chart (y = 3x + 4)")
[Link]("x")
[Link]("y")
[Link](True)
[Link]()
Two charts in a single program:

Write a python code to generate a dataset with two variables where y = 2x2 + 8
and plot a line chart and a bar chart.

import numpy as n
import [Link] as p
x = [Link](0, 11,1)
y = 2*x*x + 8

[Link](x,y)
[Link]("Bar chart ")
[Link]("x")
[Link]("y")
[Link](True)
[Link]()

[Link](x,y)
[Link]("Line chart ")
[Link]("x")
[Link]("y")
[Link](True)
[Link]()
Write a program that draws box plot of marks of ten students.

import [Link] as p
marks = [12,45,18,25,65,12,89,0, 23, 35]
[Link](marks)
[Link]("Box Plot")
[Link]("Marks Distribution ")
[Link](True)
[Link]()

Write a program that shows histogram of marks of ten students.

import [Link] as p
marks = [12,45,18,25,65,12,89,0, 23, 35]
[Link](marks)
[Link]("Historgram")
[Link]("Marks Intervals ")
[Link]("Frquency ")
[Link](True)
[Link]()

Write a program that draws pie-chart for following scenario.


Grade Total Students Grade Total Students
A 6 B 2
C 10 D 3

import [Link] as p
[Link]([6,2,10,2], labels = ['A','B','C','D'], autopct = '%1.1f%%')
[Link]('Grade Distribution Graph')
[Link]()
Practical Paper Pre Board and Model Paper Programs (Top)

Write a Python program that asks the user whether a book is "on time" or
"late."
a) If the book is "on time," print "Book returned on time." If the book is
"late," print "Book is late."

n = input("Enter Status : on time or late ")


if n == "on time":
print("Book Returned on Time ")
elif n == "late":
print("Book is Late ")
else:
print("Invalid input ")

b) Modify the program to enter the return status for eight (08) books using
a loop.

for i in range(1,9, 1):


n = input("Enter Status : on time or late ")
if n == "on time":
print("Book Returned on Time ")
elif n == "late":
print("Book is Late ")
else:
print("Invalid input ")

c) After tracking all eight books, print the total number of books that were
returned on time.
count = 0
for i in range(1,9, 1):
n = input("Enter Status : on time or late ")
if n == "on time":
print("Book Returned on Time ")
count = count + 1
elif n == "late":
print("Book is Late ")
else:
print("Invalid input ")

print("Total Books Returned on time ", count)


d) Add a feature to calculate and print the percentage of books that were
returned late.

count = 0
for i in range(1,9, 1):
n = input("Enter Status : on time or late ")
if n == "on time":
print("Book Returned on Time ")
elif n == "late":
print("Book is Late ")
count = count + 1
else:
print("Invalid input ")

per = count*100/8
print("Percentage of Books returned late ", per)

You are recording scores of a cricketer he made in ten matches. Use python list to
perform following operations.
a) Store following data of scores in a python list and print it:
[45, 12, 0, 35, 122, 119, 0, 77, 66, 0]

scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]


print(scores)

b) What does the following python code prints?


scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]
print(max(scores))
for i in scores:
if i>=50 and i<100:
print(i)

Output:
122
77
66
c) Examine the following python program, identify any errors and correct them.

scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]


print(scores[10])
sum = 1
for i in range(1, 11, 1):
sum = sum + score[i]
avg = sum/9
print(avg)

scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]


print(scores[9])
sum = 1
for i in range(0, 10, 1):
sum = sum + scores[i]
avg = sum/10
print(avg)
d) Modify following code to count the number of centuries along with ducks as
well.

scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]


count = 0
for i in range(10):
if scores[i] == 0:
count = count + 1
print("Number of Ducks = ", count)

scores = [45, 12, 0, 35, 122, 119, 0, 77, 66, 0]


count = 0
centuries = 0
for i in range(10):
if scores[i] == 0:
count = count + 1
if scores[i] >= 100:
centuries = centuries + 1

print("Number of Ducks = ", count)


print("Number of Centuries ",centuries)

File Handling (Top)

Write a program that opens a file in write mode and gets input from user and
write on the file.
Method 1

f = open("[Link]", "w")
s = input("Enter String ")
[Link](s)
[Link]()
Method 2 – using with

with open("[Link]", "w") as f:


s = input("Enter String ")
[Link](s)

Write a program that opens a file in read mode and reads the data in the file.

Method 1

f = open("[Link]", "r")
s = [Link]()
print(s)
[Link]()

Method 2 – using with

with open("[Link]", "r") as f:


s = [Link]()
print(s)

Write a program that open a file and read its contents line by line. Print the
content of the file line by line.
Method 1
file = open("[Link]", "r")
for line in file:
print(line, end="")
[Link]()

Method 2 – using with

with open("[Link]", "r") as file:


for line in file:
print(line, end="")
Error Handling (Top)

Write a program that inputs two numbers and divides them. Implement
suitable error handling exceptions.

try:
n1 = int(input("Enter first number "))
n2 = int(input("Enter second number "))
res = n1/n2
print("Division Result ",res)
except ValueError:
print("You have given invalid input - Please Enter Number ")
except ZeroDivisionError:
print("Number Cannot be divided by zero ")

Write a program that makes a list and print any out of range index. The
program should handle the error.

try:
n = [4, 10, 15, 7, 50]
print(n[8])
except IndexError:
print("You have given wrong index ")

Write a program that opens a file in read mode and handles error if the file is
not found.

try:
f = open("D:\\[Link]", "r")
s = [Link]()
print(s)
except FileNotFoundError:
print("You have given wrong file or path name, File not Found ")

You might also like