Professional Documents
Culture Documents
PRACTICAL FILE
5 Python Strings Write a menu driven program to accept two strings from
the user and perform the various functions using user
defined functions.
17 Python Module
Write a program that defines a function large in a
module which will be used to find larger of two values
and called from CODE in another module
18 Python File Write a program to know the cursor position and print
Handling the text according to specifications given below:
● Print the initial position
● Move the cursor to 4th position
● Display next 5 characters
● Move the cursor to the next 10 characters
● Print the current cursor position
● Print next 10 characters from the current cursor
position
19 Recursion Write a program to get the factorial of any number.
20 Python File Write a program to Create a CSV file by entering user-
Handling - CSV id and password, read and search the password for given
File user id
Basics of Python Programming BCA-(211)
PROGRAM-1
OBJECTIVE: Write a program to enter two integers, two floating numbers and then perform all
arithmetic operations on them.
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
int1 = int(input("Enter an integer: "))
int2 = int(input("Enter another integer: "))
float1 = float(input("Enter a floating point number: "))
float2 = float(input("Enter another floating point number: "))
sum = int1 + int2
difference = int1 - int2
product = int1 * int2
quotient = int1 / int2
modulus = int1 % int2
float_sum = float1 + float2
float_difference = float1 - float2
float_product = float1 * float2
float_quotient = float1 / float2
print("Sum of integers:", sum)
print("Difference of integers:", difference)
print("Product of integers:", product)
print("Quotient of integers:", quotient)
print("Modulus of integers:", modulus)
print("Sum of floating point numbers:", float_sum)
print("Difference of floating point numbers:", float_difference)
print("Product of floating point numbers:", float_product)
print("Quotient of floating point numbers:", float_quotient)
OUTPUT:
PROGRAM-2
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def is_armstrong(n):
num_digits = len(str(n))
sum_digits = 0
for digit in str(n):
sum_digits += int(digit) ** num_digits
return sum_digits ==n
print(is_armstrong(153)) # Output: True
print(is_armstrong(123)) # Output: False
print(is_armstrong(502)) # Output: False
print(is_armstrong(371)) # Output: True
print(is_armstrong(9474)) # Output: True
OUTPUT:
PROGRAM-3
OBJECTIVE: Write a program to print the sum of all the primes between two ranges.
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def sum_primes(start, end):
sum = 0
for i in range(start, end+1):
if is_prime(i):
sum += i
return sum
print(sum_primes(10, 20))
OUTPUT:
PROGRAM-4
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def swap_strings(s1,s2):
s1,s2=s2,s1
return s1,s2
s1="Hello"
s2="World"
print(s1,s2,swap_strings(s1,s2))
OUTPUT:
PROGRAM-5
OBJECTIVE: Write a menu driven program to accept two strings from the user and perform the
various functions using user defined functions.
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def main():
print("1. Concatenate the two strings\n2. Compare the two strings\n3. Find the length of the two strings\
n4. Convert the strings to uppercase\n5. Convert the strings to lowercase\n6. Quit")
choice = int(input("Enter your choice: "))
string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")
if choice == 1:
concatenate(string1, string2)
elif choice == 2:
compare(string1, string2)
elif choice == 3:
find_length(string1, string2)
elif choice == 4:
convert_to_uppercase(string1, string2)
elif choice == 5:
convert_to_lowercase(string1, string2)
elif choice == 6:
quit()
else:
print("Invalid choice")
def concatenate(string1, string2):
result = string1 + string2
print("The concatenated string is:", result)
def compare(string1, string2):
if string1 == string2:
print("The strings are equal")
else:
print("The strings are not equal")
def find_length(string1, string2):
length1 = len(string1)
length2 = len(string2)
print("The length of the first string is:",length1,"\nThe length of the second string is:",length2)
def convert_to_uppercase(string1, string2):
result1 = string1.upper()
result2 = string2.upper()
print("The uppercase of the first string is:",result1,"\nThe uppercase of the second string is:",result2)
def convert_to_lowercase(string1, string2):
result1 = string1.lower()
result2 = string2.lower()
print("The lowercase of the first string is:",result1,"\nThe lowercase of the second string is:",result2)
main()
OUTPUT:
PROGRAM-6
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def find_min_max(numbers):
min_num = float('inf')
max_num = float('-inf')
for num in numbers:
if num < min_num:
min_num = num
if num > max_num:
max_num = num
return (min_num, max_num)
print(find_min_max([3, 5, 1, 2, 4])) # (1, 5)
print(find_min_max([-3, 5, 1, 2, 4])) # (-3, 5)
OUTPUT:
PROGRAM-7
OBJECTIVE: Create a dictionary whose keys are month names and whose values are the number
of days in the corresponding months.
• Ask the user to enter a month name and use the dictionary to tell them how many days are
in the month
• Print out all keys in the alphabetically order
• Print out all the months with 31 days
• Print out the key value pairs sorted by number of days in each month
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
month_days = {"January": 31,"February": 28,"March": 31,"April": 30,"May": 31,"June": 30,"July":
31,"August": 31,"September": 30,"October": 31,"November": 30,"December": 31}
month = input("Enter a month name: ")
days = month_days[month]
print(f"There are {days} days in {month}.","\nMonths in alphabetical order: ")
for month in sorted(month_days.keys()):
print(month,end=", ")
print("\nAll month with 31 days : ")
for month, days in month_days.items():
if days == 31:
print(month,end=", ")
print("\nSorte by number of days : ")
for month, days in sorted(month_days.items(), key=lambda x: x[1]):
print(f"{month}: {days} days",end=", ")
OUTPUT:
PROGRAM-8
OBJECTIVE: Make a list of first 10 letters of the alphabet, then use the slicing to do the following
operations:
• Print the first 3 letters of the list
• Print any 3 letters from the middle
• Print the letter from any particular index to the end of the list
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
print(letters[:3])
print(letters[3:6])
print(letters[4:])
OUTPUT:
PROGRAM-9
OBJECTIVE: Write a program that scans an email address and forms a tuple of user name and
domain.
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def parse_email(email):
user_name, domain = email.split('@')
return (user_name, domain)
email = "рири7479@discord.com"
print(parse_email(email))
OUTPUT:
PROGRAM-10
OBJECTIVE: Write a program that uses a user defined function that accepts name and gender (as
M for Male, F for Female) and prefixes Mr./Ms. on the basis of the gender.
CODE:
print("NAME: Ravi Mandal Enrollment No: 05790302021")
def prefix_name(name, gender):
if gender == "M":
return "Mr." + name
elif gender == "F":
return "Ms." + name
else:
return "Error: Invalid gender"
print(prefix_name("рири", "M")) # prints "Mr. John"
print(prefix_name("Siya", "F")) # prints "Ms. Jane"
print(prefix_name("Karan", "G")) # prints "Error: Invalid gender"
OUTPUT:
PROGRAM-11
CODE:
def menu():
print("List Operations")
print("1. Print List")
print("2. Append Element")
print("3. Remove Element")
print("4. Find Element")
print("5. Exit")
choice = input("Enter your choice: ")
return int(choice)
def show_list(lst):
print(lst)
def append_element(lst):
element = input("Enter the element to append: ")
lst.append(element)
print("Element", element, "appended to the list")
def remove_element(lst):
element = input("Enter the element to remove: ")
if element in lst:
lst.remove(element)
print("Element", element, "removed from the list")
else:
print("Element not found in the list")
def find_element(lst):
element = input("Enter the element to find: ")
if element in lst:
print("Element", element, "found in the list")
else:
print("Element not found in the list")
lst = ["рири","Ram","Siya","Ravi Mandal"]
while True:
choice = menu()
if choice == 1:
show_list(lst)
elif choice == 2:
append_element(lst)
elif choice == 3:
remove_element(lst)
elif choice == 4:
find_element(lst)
elif choice == 5:
break
else:
print("Invalid choice")
OUTPUT:
PROGRAM-12
OBJECTIVE: Write a program to display Bar graphs, Pie Chat using Matplotlib.
CODE:
import matplotlib.pyplot as plt
print("NAME: Ravi Mandal Enrollment No: 05790302021")
data = [3, 10, 7, 5, 3, 4.5, 6, 8.1]
plt.bar(range(len(data)), data)
plt.show()
labels = ['A', 'B', 'C', 'D']
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()
OUTPUT:
PROGRAM-13
OBJECTIVE: Write a program that defines a function large in a module which will be used to find
larger of two values and called from CODE in another module.
CODE:
Largest.py:
def large(a, b):
if a > b:
return a
else:
return b
Main.py:
import largest
print("NAME: Ravi Mandal Enrollment No: 05790302021")
larger_value = largest.large(3,7)
print(larger_value) # prints 20
OUTPUT:
PROGRAM-14
OBJECTIVE: Write a program to know the cursor position and print the text according to
specifications given below:
• Print the initial position
• Move the cursor to 4th position
• Display next 5 characters
• Move the cursor to the next 10 characters
• Print the current cursor position
• Print next 10 characters from the current cursor position
CODE:
import io
print("NAME: Ravi Mandal Enrollment No: 05790302021")
buffer = io.StringIO()
buffer.write("Hello, world!\n")
print("Initial cursor position:", buffer.tell())
buffer.seek(3)
print("Next 5 characters:", buffer.read(5))
buffer.seek(10,0)
print("Current cursor position:", buffer.tell())
print("Next 10 characters:", buffer.read(10))
OUTPUT:
PROGRAM–15
CODE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num = int(input("Enter a number: "))
print("The factorial of", num, "is", factorial(num))
OUTPUT:
PROGRAM-16
OBJECTIVE: Write a program to Create a CSV file by entering user-id and password, read and
search the password for given user id
CODE:
import csv
print("NAME: Ravi Mandal Enrollment No: 05790302021")
# Create a CSV file with a user ID and password
def create_csv(filename):
with open(filename, 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
csv_writer.writerow(['user_id', 'password'])
while True:
user_id = input('Enter user ID (enter "qq" to quit): ')
if user_id == 'qq':
break
password = input('Enter password: ')
csv_writer.writerow([user_id, password])
def search_csv(filename, user_id):
with open(filename, 'r') as csvfile:
csv_reader = csv.reader(csvfile)
next(csv_reader) # skip the header row
for row in csv_reader:
if row[0] == user_id:
return row[1]
return None
filename = 'passwords.csv'
create_csv(filename)
user_id = input('Enter user ID to search: ')
password = search_csv(filename, user_id)
if password:
print(f'The password for user ID "{user_id}" is: {password}')
else:
print(f'User ID "{user_id}" not found')
OUTPUT: