[go: up one dir, main page]

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

Python Programs

The document outlines various Python laboratory programs covering topics such as data types, string manipulation, operators, flow control, loops, functions, lists, dictionaries, and string manipulation functions. Each program includes code snippets and example outputs demonstrating functionalities like calculating areas, converting temperatures, grading systems, and manipulating lists and dictionaries. The document serves as a comprehensive guide for practicing Python programming concepts through practical examples.

Uploaded by

deekshasn18
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 views26 pages

Python Programs

The document outlines various Python laboratory programs covering topics such as data types, string manipulation, operators, flow control, loops, functions, lists, dictionaries, and string manipulation functions. Each program includes code snippets and example outputs demonstrating functionalities like calculating areas, converting temperatures, grading systems, and manipulating lists and dictionaries. The document serves as a comprehensive guide for practicing Python programming concepts through practical examples.

Uploaded by

deekshasn18
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
You are on page 1/ 26

LABORATORY PROGRAMS

Program 1: Programs on data types, string concatenation and replication

Python program to find the area of a circle:

def area_of_circle(r):
Pi = 3.142
return Pi * (r * r)

r = float(input("Enter the radius value: "))


circumference = 2 * Pi * r
area = area_of_circle(r)

print(f"The circumference of the circle is: {circumference}")


print(f"The area of the circle is: {area}")

Output:
Enter the radius value: 2
The circumference of the circle is: 12.56
The area of the circle is: 12.56

Python program to convert the temperature in degrees Fahrenheit to


degrees Celsius:

fahrenheit = float(input("Enter temperature in Fahrenheit: "))


celsius = (fahrenheit - 32) * 5/9
print(str(fahrenheit) + " degree Fahrenheit is equal to " + str(celsius) + " degree
Celsius.")

Output:

Enter temperature in Fahrenheit: 100


100.0 degree Fahrenheit is equal to 37.7777777778 degree Celsius.
Python program to calculate the area of a triangle given base and height:

b = int(input("Input the base: "))


h = int(input("Input the height: "))
area = b * h / 2

print("Area = ", area)

Output:

Input the base: 5


Input the height: 2
Area = 5.0

Program for string replication and concatenation

string = "hello"
result = string * 3
print(result)

Output:
hellohellohello

a = ["hello", "world", "python"]


a = [x * 2 for x in a]
print(a)

Output:
['hellohello', 'worldworld', 'pythonpython']
Program 2: Program on operators and Flow Control

Python program that prints a user's grade given a percent of points


achieved. The program should prompt the user to enter his/her percent of
points. It should then print a letter grade A, A-, B+, B, B-, C+, C, C-, D+, D,
D- and F as shown in the table below:

Grade Equal to or Greater than


A 93.33
A- 90
B+ 86.67
B 83.33
B- 80
C+ 76.67
C 73.33
C- 70
D+ 66.67
D 63.33
D- 60
F 0

while True:
point = float(input("Enter your scored point (0-100) for grading: "))

if point > 100:


print('Max. marks is 100!!!')
elif point >= 93.33:
print('A')
elif point >= 90:
print('A-')
elif point >= 86.67:
print('B+')
elif point >= 83.33:
print('B')
elif point >= 80:
print('B-')
elif point >= 76.67:
print('C+')
elif point >= 73.33:
print('C')
elif point >= 70:
print('C-')
elif point >= 66.67:
print('D+')
elif point >= 63.33:
print('D')
elif point >= 60:
print('D-')
elif point >= 0:
print('F')
else:
print('Invalid input')
break

Output:

1) Enter your scored point (0-100) for grading: 85


B

2) Enter your scored point (0-100) for grading: 101


Max. marks is 100!!!

3) Enter your scored point (0-100) for grading: 50


F

4) Enter your scored point (0-100) for grading: -1


Invalid input

Python program to check whether a given year is a leap year or not:

year = int(input("Enter a year: "))

if (year % 400 == 0) and (year % 100 == 0):


print("{0} is a leap year".format(year))
elif (year % 4 == 0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
Output:

1) Enter a year: 2000


2000 is a leap year

2) Enter a year: 1900


1900 is not a leap year
Program 3: Programs on loops

Python program to find the average of N numbers:

num = int(input('How many numbers: '))


total_sum = 0

for n in range(num):
numbers = float(input('Enter number: '))
total_sum += numbers

avg = total_sum / num

print('Average of', num, 'numbers is:', avg)

Output:

How many numbers: 5


Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
Average of 5 numbers is: 3.0

Python program to print the Fibonacci series between a given range:

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


num1 = 0
num2 = 1
next_num = num2
count = 1

print("0 1", end=" ")

while count < n:


print(next_num, end=" ")
count += 1
num1, num2 = num2, next_num
next_num = num1 + num2
print()
Output:

Enter the range value: 7


0112358

Python program to print even numbers, odd numbers, and prime numbers
between a given range using loop and range:

lower = int(input("Enter lower limit value: "))


upper = int(input("Enter upper limit value: "))

print("Even numbers between", lower, "and", upper, "are: ")


for num in range(lower, upper + 1):
if num % 2 == 0:
print(num, end=" ")

print("\nOdd numbers between", lower, "and", upper, "are: ")


for num in range(lower, upper + 1):
if num % 2 != 0:
print(num, end=" ")

print("\nPrime numbers between", lower, "and", upper, "are: ")


for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num, end=" ")

Output:

Enter lower limit value: 1


Enter upper limit value: 9
Even numbers between 1 and 9 are: 2 4 6 8
Odd numbers between 1 and 9 are: 1 3 5 7 9
Prime numbers between 1 and 9 are: 2 3 5 7
Python program to demonstrate the working of break and continue
statements:

for i in range(1, 11):


if i == 6:
continue
else:
print(i, end=" ")

print('\n')

for i in range(1, 11):


if i == 6:
break
else:
print(i, end=" ")

Output:

1 2 3 4 5 7 8 9 10

12345
Program 4: Programs on functions

Write a python program to find the factorial of the given number using a
recursive function.

def recur_factorial(n):
if n == 1:
return 1
else:
return n * recur_factorial(n - 1)

num = int(input("Enter a number: "))

if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

Output:

1) Enter a number: 5
The factorial of 5 is 120

2) Enter a number: -10


Sorry, factorial does not exist for negative numbers.

Write a function called is_prime, which checks if a number is prime.

def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

num = int(input("Enter a Number: "))


if is_prime(num):
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number.")

Output:

1) Enter a number: 23
23 is a prime number.

2) Enter a number: 25
25 is not a prime number.

Write a python program to return a value from the function.

def find_square(num):
result = num * num
return result

square = find_square(3)
print('Square:', square)

Output:-
Square: 9
Program 5: Programs on lists

Read N numbers from the console and create a list. Develop a program to
print mean, variance & standard deviation with suitable messages.

from math import sqrt

myLst = []

num = int(input("Enter the number of elements in your list: "))

for i in range(num):
val = int(input("Enter the element: "))
myLst.append(val)

print("The length of list is", len(myLst))


print("List contents", myLst)

total = 0

for elem in myLst:


total += elem

mean = total / num

total = 0

for elem in myLst:


total += (elem - mean) * (elem - mean)

Variance = total / num


StdDev = sqrt(Variance)

print("Mean = ", mean)


print("Variance = ", Variance)
print("Standard deviation = ", "%.2f" % StdDev)
Output:

Enter the number of elements in your list: 3


Enter the element: 10
Enter the element: 20
Enter the element: 30
The length of list 1 is 3
List contents [10, 20, 30]
Mean = 20.0
Variance = 66.66666666666667
Standard deviation = 8.16

Declare a list variable named IT companies and assign initial values:


Facebook, Google, Microsoft, Apple, IBM, Oracle, and Amazon.

i. Sort the list using the sort() method.


ii. Reverse the list in descending order using the reverse() method.
iii. Slice out the first 3 companies from the list.
iv. Slice out the last 3 companies from the list.
v. Slice out the middle IT company or companies from the list.
vi. Remove the first IT company from the list.
vii. Remove the middle IT company or companies from the list.
viii. Remove the last IT company from the list.

IT_companies = ["Facebook", "Google", "Microsoft", "Apple", "IBM", "Oracle",


"Amazon"]
print("Original List:", IT_companies)

IT_companies.sort()
print("Sorted List:", IT_companies)

IT_companies.reverse()
print("Reversed List:", IT_companies)

first_three = IT_companies[0:3]
print("First 3 Companies:", first_three)

last_three = IT_companies[-3:]
print("Last 3 Companies:",last_three)

middle_index = len(IT_companies) // 2
if len(IT_companies) % 2 == 0:
middle_companies = IT_companies[middle_index - 1:middle_index + 1]
print("Middle Companies:", middle_companies)
else:
middle_company = IT_companies[middle_index]
print("Middle Company:", middle_company)

del IT_companies[0]
print("After removing first company:", IT_companies)

mid_index_after_del = len(IT_companies) // 2
if len(IT_companies) % 2 == 0:
del IT_companies[mid_index_after_del - 1: mid_index_after_del + 1]
print("After removing middle company:", IT_companies)
else:
del IT_companies[mid_index_after_del]
print("After removing middle company:", IT_companies)

del IT_companies[-1]
print("After removing last company:", IT_companies)

Output:

Original List: ['Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon']


Sorted List: ['Amazon', 'Apple', 'Facebook', 'Google', 'IBM', 'Microsoft', 'Oracle']
Reversed List: ['Oracle', 'Microsoft', 'IBM', 'Google', 'Facebook', 'Apple', 'Amazon']
First 3 Companies: ['Oracle', 'Microsoft', 'IBM']
Last 3 Companies: ['Facebook', 'Apple', 'Amazon']
Middle Company: Google
After removing first company: ['Microsoft', 'IBM', 'Google', 'Facebook', 'Apple', 'Amazon']
After removing middle company: ['Microsoft', 'IBM', 'Apple', 'Amazon']
After removing last company: ['Microsoft', 'IBM', 'Apple']
Program 6: Programs on Dictionaries

Create a Student dictionary & add:


first_name, last_name, gender, age, marital status, Skills, country, city & address
as keys for the dictionary.

i. Get the length of the student dictionary.


ii. Get the value of skills & check the data type; it should be a list.
iii. Modify the skills values by adding one or two skills.
iv. Get the dictionary keys as a list.
v. Get the dictionary values as a list.
vi. Change the dictionary to a list of type tuples using the items() method.
vii. Delete one of the items in the dictionary.

person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 25,
'country': 'Finland',
'is_married': True,
'Skills': ['Javascript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {'Street': 'Space Street', 'Zipcode': '02210'}
}

print(len(person))
print(person.values())
print(person.items())

del person['age']
print(person)

Output:

7
dict_values(['Asabeneh', 'Yetayeh', 25, 'Finland', True, ['Javascript', 'React', 'Node',
'MongoDB', 'Python'], {'Street': 'Space Street', 'Zipcode': '02210'}])
dict_items([('first_name', 'Asabeneh'), ('last_name', 'Yetayeh'), ('age', 25), ('country',
'Finland'), ('is_married', True), ('Skills', ['Javascript', 'React', 'Node', 'MongoDB',
'Python']), ('address', {'Street': 'Space Street', 'Zipcode': '02210'})])
{'first_name': 'Asabeneh', 'last_name': 'Yetayeh', 'country': 'Finland', 'is_married':
True, 'Skills': ['Javascript', 'React', 'Node', 'MongoDB', 'Python'], 'address': {'Street':
'Space Street', 'Zipcode': '02210'}}
Write a python program to count occurrences of each character in the message
using the dictionary and pprint() function.

import pprint

message = "It was a bright cold day in April, and the clocks were striking thirteen."

count = {}

for character in message:


count.setdefault(character, 0)
count[character] = count[character] + 1

pprint.pprint(count)

Output:

{' ': 13,


',': 1,
'.': 1,
'A': 1,
'I': 1,
'a': 4,
'b': 1,
'c': 3,
'd': 3,
'e': 5,
'g': 2,
'h': 3,
'i': 6,
'k': 2,
'l': 3,
'n': 4,
'o': 2,
'p': 1,
'r': 5,
's': 3,
't': 6,
'w': 2,
'y': 1}
Program 7: Programs on String Manipulation Functions

Write a python program that repeatedly asks users for their age and a password
until they provide valid input. (Age should be an integer value & password must
contain only alphanumeric characters)

while True:
print("Enter your age:")
age = input()
if age.isdigit():
print("Your age:", age)
break
print("Please enter a number for your age.")

while True:
print("Select a new password (letters & numbers only):")
password = input()
if password.isalnum():
print("Selected password is:", password)
break
print("Passwords can only have letters and numbers?")

Output:

Enter your age:


Four two
Please enter a number for your age.
Enter your age:
42
Your age: 42
Select a new password (letters and numbers only):
iglobalise@123
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
globalise123
Write a python program to initialize a string as "python" and print the output as
follows:

P Python
Py Pytho
Pyt Pyth
Pyth Pyt
Pytho Py
Python P

str1 = "Python"

for i in range(len(str1)):
print(str1[:i+1].ljust(12-i), str1[0:6-i].rjust(12))

Output:

P Python
Py Pytho
Pyt Pyth
Pyth Pyt
Pytho Py
Python P
Program 8: Programs on Pattern Matching with Regular Expressions

Write a Python program to handle the following cases using regular expression
module functionalities:

i. Retrieve all the lines that contain "This" in the beginning of the line.
ii. Repeat Q1 but retrieve both upper and lower case letters.
iii. Retrieve all lines that contain consecutive 'te's.
iv. Retrieve lines that contain words of any length starting with 'S' and
ending with 'e'.
v. Retrieve all lines with a date in the form of: 1 or 2 digits, a dot, 1 or 2
digits, a dot, 2 digits.

import re

file = open('text.txt', 'r')


text = file.readlines()
file.close()

kw = re.compile(r'^This')
for line in text:
if kw.search(line):
print('i.', line, end='')

file = open('text.txt', 'r')


text = file.readlines()
file.close()

kw = re.compile(r'^this', re.IGNORECASE)
for line in text:
if kw.search(line):
print('ii.', line, end='')

file = open('text.txt', 'r')


text = file.readlines()
file.close()

kw = re.compile(r'(te){2}')
for line in text:
if kw.search(line):
print('iii.', line, end='')

file = open('text.txt', 'r')


text = file.readlines()
file.close()

kw = re.compile(r'\bS\S*e\b')
for line in text:
if kw.search(line):
print('iv.', line, end='')

file = open('text.txt', 'r')


text = file.readlines()
file.close()

kw = re.compile(r'\d\d?\.\d\d?\.\d\d')
for line in text:
if kw.search(line):
print('v.', line, end='')

Output:

Create a text file by the name ‘text.txt’ with content that matches with all the regular
expression.

Sample content of text.txt file:


This is the first line
this is the second line
Karnataka Statete 123
Date 08.12.24

Output of the code:


i. This is the first line
ii. This is the first line
ii. this is the second line
iii. Karnataka Statete 123
iv. Karnataka Statete 123
v. Date 08.12.24
Write a Python program to extract year, month, and date from a URL.

import re

def extract_date(url):
return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url)

url1 = "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-
beckhams-fame-rests-on-stupid-little-ball-josh-norman-tells-author/"

print(extract_date(url1))

Output:

[('2016', '09', '02')]


Program 9: Programs on Pattern Matching with Regular Expressions

Python program to convert a date of yyyy-mm-dd format to dd-mm-yyyy

import re

def change_date_format(dt):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', r'\3-\2-\1', dt)

dt1 = "2026-01-02"

print("Original date in YYYY-MM-DD format:", dt1)


print("New date in DD-MM-YYYY format:", change_date_format(dt1))

Output:

Original date in YYYY-MM-DD format: 2026-01-02


New date in DD-MM-YYYY format: 02-01-2026
Write a Python program that matches a string that has an 'a' followed by zero or
more 'b's.

import re

def text_match(text):
pattern = '^a(b*)$'
if re.search(pattern, text):
return "Found a match!"
else:
return "Not matched!"

print(text_match("ac"))
print(text_match("abc"))
print(text_match("a"))
print(text_match("ab"))
print(text_match("abb"))

Output:

Not matched!
Not matched!
Found a match!
Found a match!
Found a match!
Program 10: Programs on File Handling

Write a Python program to read an entire text file.

def file_read(fname):
text = open(fname)
print(text.read())

file_read('test.txt')

Create a file named ‘test.txt’ with some content.


The same content will be read and displayed as output.

Sample content to test.txt file:


Welcome to W3 resource.com.
Append this text. Append this text. Append this text.
Append this text.
Append this text.
Append this text.
Append this text.

Output:
Welcome to W3 resource.com.
Append this text. Append this text. Append this text.
Append this text.
Append this text.
Append this text.
Append this text.
Write a python program to append text to a file and display the text.

def file_read(fname):
from itertools import islice
with open(fname, "w") as myfile:
myfile.write("Python Exercises\n")
myfile.write("Java Exercises")

txt = open(fname)
print(txt.read())

file_read('abc.txt')

Output:
Python Exercises
Java Exercises
Write a program that reads a file and displays all of the words in it that are
misspelled. Misspelled words will be identified by checking each word in the file
against a list of known words. (Use file to store known words and misspelled
words).

Note:

Create input.txt with the following data:


Gooogle
Pyon
Programming
Create output.txt with the following data:
Google
Python
Programming
Application

try:
infile = open("input.txt", 'r')
except:
print("Failed to open the file for reading...Quitting")
quit()

valid = {}
words_file = open("output.txt", 'r')
for i in words_file:
i = i.lower().rstrip()
valid[i] = 0
words_file.close()

misspelled = []
for i in infile:
if i.strip().lower() not in valid and i.strip() not in misspelled:
misspelled.append(i)

infile.close()

if len(misspelled) == 0:
print("No words were misspelled")
else:
print("Following words are misspelled:")
for word in misspelled:
print(word, end='')
Output:

Following words are misspelled:


Gooogle
Pyon

You might also like