Python Programs
Python Programs
def area_of_circle(r):
Pi = 3.142
return Pi * (r * r)
Output:
Enter the radius value: 2
The circumference of the circle is: 12.56
The area of the circle is: 12.56
Output:
Output:
string = "hello"
result = string * 3
print(result)
Output:
hellohellohello
Output:
['hellohello', 'worldworld', 'pythonpython']
Program 2: Program on operators and Flow Control
while True:
point = float(input("Enter your scored point (0-100) for grading: "))
Output:
for n in range(num):
numbers = float(input('Enter number: '))
total_sum += numbers
Output:
Python program to print even numbers, odd numbers, and prime numbers
between a given range using loop and range:
Output:
print('\n')
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)
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
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
Output:
1) Enter a number: 23
23 is a prime number.
2) Enter a number: 25
25 is not a prime number.
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.
myLst = []
for i in range(num):
val = int(input("Enter the element: "))
myLst.append(val)
total = 0
total = 0
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:
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 = {}
pprint.pprint(count)
Output:
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:
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
kw = re.compile(r'^This')
for line in text:
if kw.search(line):
print('i.', line, end='')
kw = re.compile(r'^this', re.IGNORECASE)
for line in text:
if kw.search(line):
print('ii.', line, end='')
kw = re.compile(r'(te){2}')
for line in text:
if kw.search(line):
print('iii.', line, end='')
kw = re.compile(r'\bS\S*e\b')
for line in text:
if kw.search(line):
print('iv.', line, end='')
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.
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:
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"
Output:
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
def file_read(fname):
text = open(fname)
print(text.read())
file_read('test.txt')
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:
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: