CS3203 Python Lab manual
CS3203 Python Lab manual
AIM:
To write a program to find the greatest of three number using python.
ALGORITHM:
Step 1: Start
Step 2: Input three numbers: a, b, c.
Step 3: Check:If a > b and a > c: print “a is the greatest”.
Step 4: Else if b > a and b > c: print “b is the greatest”. Else: print “ c is the greatest”.
Step 5: End
PROGRAM:
a=int(input("Enter the First number:"))
b=int(input("Enter the Second number:"))
c=int(input("Enter the Third number:"))
if (a>b)&(a>c):
print("%d is Greater" %(a))
elif (b>a)&(b>c):
print("%d is Greater" %(b))
else:
print("%d is Greater" %(c))
OUTPUT:
Enter the First number: 5
Enter the Second number: 4
Enter the Third number: 7
7 is Greater
RESULT:
Thus the program to find the greatest of three numbers is written and executed successfully.
Ex No: 2 FIBONACCI SERIES BY USING LOOPING CONSTRUCTS
AIM:
To display the Fibonacci series by using looping constructs
ALGORITHM:
Step 1: Start
Step 2: Input the number of terms, n.
Step 3: Initialize variables:
f=0
f1 = 0
f2 = 1
Step 4: Print f1 and f2.
Step 5: Repeat the following steps for i = 3 to n:
Compute f = f1 + f2.
Print f.
Update values:f1 = f2 and f2 = f
Step 6: End the loop.
Step 7: End
Program
f=0
f1=0
f2=1
n=int(input("Enter the Range:"))
print(f1,f2,end=" ")
f=f1+f2
while f<n:
f=f1+f2
f1=f2
f2=f
print(f,end=" ")
Output:
RESULT:
Thus the Fibonacci series using looping constructs is written and executed successfully
Ex NO: 3 GCD OF TWO NUMBERS USING FUNCTION
AIM:
To find the GCD of two numbers using Function.
ALGORITHM:
Step 1: Start
Step 2: Define a function GCD(a, b):
Input: Two integers a and b.
Repeat while b ≠ 0:
Compute the remainder: remainder = a % b.
Update a = b and b = remainder.
Return a as the GCD.
Step :3 End Function
Step 4: Main Program:
Input two integers a and b.
Call the function GCD(a, b) and store the result.
Output the result as the GCD of a and b.
Step 5: End
Program
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter First Number:"))
b=int(input("Enter Second Number:"))
GCD=gcd(a,b)
print("GCD is:",GCD)
Output:
AIM:
To implement String Functions and Methods.
ALGORITHM:
Step 1: Start
Step 2: Read the String
Step 3: Implement the String Functions and Methods
Step 4: Print String
Step5: Stop
Program:
Program:
str="programming"
print(len(str))
Output:
11
2. Str.Capitaize()
This method will return a copy of the given string with the first character in uppercase and
remaining characters in lower case format.
Program:
str="programming"
print(str.capitalize())
Output:
Programming
3. Str.Upper()
This will return a copy of the given string with all the characters in Uppercase.
Program:
str="programming"
print(str.upper())
Output:
PROGRAMMING
4. Str.lower()
This will return a copy of the given string with all the characters in Lower case.
Program:
str="PROGRAMMING"
print(str.lower())
Output:
programming
5. str.count()
This method will return the total number of overlapping occurrences of the given substring with
the given range of [start,end].
Program:
6. str.find()
This method will return the lowest index of the given string which given the range of [start,end].
Program:
Output:
7
7. str.isalnum()
This method will return the Boolean Value True, if there is one character at least and one numeric
value with no space otherwise it will return False.
Program:
Output
False
True
8. Str.isalpha()
This method will return the Boolean Value True, if there is one character at least and if all the all
the characters in the string are alphabetic otherwise it will return False.
Program:
str1="Python3"
str2="Python"
print(str1.isalpha())
print(str2.isalpha())
Output
False
True
9. str.isdigit()
This method will return the Boolean Value True, if there is one character at least and if all the
characters in the given string are Numeric Value otherwise it will return False.
Program:
str1="Python"
str2="3"
print(str1.isdigit())
print(str2.isdigit())
Output
False
True
10. str.islower()
This Method will return a Boolean Value True in a case, where all the characters present in the
string are lower case otherwise it will return False.
Program:
str1="Python"
print(str1.islower())
Output
False
11. str.isupper()
This method will return a Boolean Value True in a case, where all the characters present in the
string are uppercase otherwise it will return False.
Program:
str1="PYTHON"
print(str1.islower())
Output
True
12.str.title()
This method will return a Title Case Version of the given string, where the first letter of a word is
in uppercase and the rest of the characters in the lower case.
Program:
Output
13. str.isspace()
This method will return True, if the given string contains only Whitespace otherwise it will return
False.
Program:
str1=" "
print(str1.isspace())
Output:
True
14. str.split()
This method will return a list of all the words in the string by using the split() operator. It can split
by using single quotes or double quotes.
Program:
Output:
RESULT:
Thus the String Functions and Methods program are executed successfully.
Ex NO: 5 TO DISPLAY A SIMPLE CALENDAR WITHOUT USING
CALENDAR MODULE IN PYTHON
AIM:
To display a simple calendar without using calendar module in python.
ALGORITHM:
Step 1: Start
Step 2: Input the year (year) and month (month) from the user.
Step 3: Define arrays/lists:
Days of the week: days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
Days in each month: month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Step 4: Check for a leap year:
If year % 4 == 0 and (year % 100 != 0 or year % 400 == 0), update month_days[1] = 29
(February has 29 days in a leap year).
Step 5: Determine the first day of the given month:
If month < 3, set month += 12 and year -= 1.
Compute:
day_code = (1 + 2 * month + (3 * (month + 1)) // 5 + year + year // 4 - year // 100 + year //
400) % 7
Step 6: Output the calendar:
Print the month and year header (e.g., Month Year).
Print the days of the week using the days list.
Initialize a counter for indentation (day_code).
For each day in the range 1 to month_days[month - 1]:
Print each day number, aligning with its corresponding day of the week.
Start a new line after printing Saturday.
Step 7: End
Program
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
# Get the number of days in the month and the first day of the month
days_in_month = month_days[month - 1]
first_day = get_first_day_of_month(year, month)
Output:
RESULT:
Thus the program to display Simple Calendar in python program without using the
calendar module was executed successfully.
Ex NO: 6 A LINEAR SEARCH
AIM:
Write a program to search an element in a list using linear search concept in python.
ALGORITHM:
Step 1: Start
Step 2: Input a list of elements (list1) and a search element.
Step 3: Initialize: A variable found = False to track whether the element is found.
Step 4: Iterate over the list using a loop:
For each element in list1, check:
If the current element is equal to search:
Set found = True.
Print the output as "Element found at position <index>" (index starts from 1).
Break the loop.
Step 5: Check:
If found == False:
Print the output as "Element not found".
Step 6: End
PROGRAM:
list1=[4,1,2,5,3]
search=int(input("Enter the Search Number:"))
found=False
for i in range(0,len(list1)):
if search==list1[i]:
print("%d Number is Found in the Position:%d" %(search,i))
found=True
if found==False:
print("%d Number is Not Found in the List" %(search))
OUTPUT:
Enter the Search Number: 5
RESULT:
Thus the program for linear search is written and executed successfully.
EX NO: 6 B BINARY SEARCH
AIM:
Write a program to search an element in a list using binary search concept in python.
ALGORITHM:
Step 1: Start
Step 2: Input a sorted list arr and the target element target.
Step 3: Initialize:
first = 0 (index of the first element in the list)
last = len(arr) - 1 (index of the last element in the list)
found = False (to track if the element is found)
Step 4: Repeat while first <= last and found == False:
Calculate the middle index: mid = (first + last) // 2.
Check:
If arr[mid] == target:
Set found = True.
Print: "Element found at position <mid>" (position starts from 0).
Break the loop.
Else if target < arr[mid]:
Update last = mid - 1 (search in the left half).
Else:
Update first = mid + 1 (search in the right half).
Check:
If found == False:
Print "Element not found".
Step 5:End
PROGRAM:
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
print("Element found in the position:",mid)
else:
if item < item_list[mid]:
last = mid - 1
else:
first = mid + 1
if (found == False):
print("Element not found")
a=[]
n=int(input("Enter the number of elements:"))
for i in range(0,n):
b=int(input("Enter the element:"))
a.append(b)
x=int(input("Enter the number to be searched:"))
binary_search(a,x)
OUTPUT:
Enter the number of elements: 5
Enter the element: 10
Enter the element: 20
Enter the element: 30
Enter the element: 40
Enter the element: 50
Enter the number to be searched: 30
Element found in the position:2
RESULT:
Thus the program for binary search is written and executed successfully.
EX NO: 7 READ THE CONTENT OF THE FILE AND CHANGE
THEM FROM LOWER TO UPPER CASE
CHARACTERS
AIM:
To read the contents of the file and change them from lower to upper case characters in
python.
ALGORITHM:
Step 1: Start the program.
Step 2: Open the file in read mode
Step 3: Read each line to calculate the word count.
for line in f:
print(line.upper())
Step 4: Print the line
Step 5: Stop the
program.
PROGRAM:
fname = input("Enter file name: ") #test.txt
with open(fname, 'r') as f:
for line in f:
print (line.upper())
hai
hello python
hai friends
OUTPUT:
Enter file name: “test.txt”
HAI
HELLO PYTHON
HAI FRIENDS
RESULT:
Thus the program to change the file from lower to upper case has been executed
successfully.
Ex NO: 8 COMMAND LINE ARGUMENTS (WORD COUNT)
AIM:
To count the words in the text file using the command line arguments in python
programming.
ALGORITHM:
PROGRAM:
hai
hello python
hai friends
OUTPUT:
RESULT:
Thus the program for word count in file has been executed successfully.
To find the most frequent words in a text file using python programming.
ALGORITHM:
PROGRAM:
hai
hello python
hai friends
OUTPUT:
RESULT:
Thus the program for most frequent words in a text file has been executed successfully.
Ex NO: 11A STUDENT MARKS STATEMENT USING DICTIONAY
AIM:
ALGORITHM:
Step 1: Start
Step 2:Input:
Student's name and store it as student['Name'].
Student's roll number and store it as student['Roll Number'].
Step 3: Input the number of subjects num_subjects.
Step 4: Initialize:
An empty dictionary student['Marks'] to store subject-wise marks.
Step 5: Repeat for each subject (from 1 to num_subjects):
Input the subject name as subject.
Input the marks for the subject as marks.
Store marks in student['Marks'] with subject as the key.
Step 6: Compute:
Total marks as the sum of all marks in student['Marks'].
Average marks as total / num_subjects.
Step7: Print the output:
Student's name, roll number, and subject-wise marks.
Total marks.
Average marks rounded to two decimal places.
If average >= 50, Output: "Result: Passed".
Else, Output: "Result: Failed".
Step 8:End
PROGRAM:
def display_marks_statement(student):
print("\n--- Student Marks Statement ---")
print(f"Name: {student['Name']}")
print(f"Roll Number: {student['Roll Number']}")
print("Subject-wise Marks:")
for subject, marks in student['Marks'].items():
print(f" {subject}: {marks}")
total = sum(student['Marks'].values())
average = total / len(student['Marks'])
print(f"Total Marks: {total}")
print(f"Average Marks: {average:.2f}")
if average >= 50:
print("Result: Passed")
else:
print("Result: Failed")
for _ in range(num_subjects):
subject = input("Enter the subject name: ")
marks = int(input(f"Enter the marks for {subject}: "))
student['Marks'][subject] = marks
OUTPUT:
RESULT:
Thus student marks statement using dictionary in python programming has been executed
successfully.
ALGORITHM:
Step 1: Start
Step 2: Input the number of items num_items.
Step 3: Initialize an empty dictionary items to store item details.
Step 4: Repeat for each item (from 1 to num_items):
Input the item name as item_name.
Input the quantity for the item as quantity.
Input the price per unit for the item as price_per_unit.
Store the item details in the dictionary items with item_name as the key and a nested
dictionary containing:
'Quantity': the value of quantity.
'Price per Unit': the value of price_per_unit.
Step 5: Initialize a variable total_amount = 0 to keep track of the total bill amount.
Step 6: Output:
Print the header for the bill: "Item Name", "Quantity", "Price per Unit", and "Total
Price".
Step 7: For each item in the dictionary:
Retrieve the item name, quantity, and price per unit.
Calculate the total price for the item as: total_price = quantity * price_per_unit.
Output the item details in a formatted way:
Item name, quantity, price per unit, and the calculated total price.
Add the total_price to total_amount for the overall bill.
Step 8: Output the total amount due:
Print the total amount of the bill.
Step 9: End
PROGRAM:
def generate_bill(item_dict):
print("\n--- Retail Bill Statement ---")
print(f"{'Item Name':<20} {'Quantity':<10} {'Price per Unit':<15} {'Total Price':<15}")
total_amount = 0
# Loop through the dictionary and print the bill details for each item
for item, details in item_dict.items():
item_name = item
quantity = details['Quantity']
price_per_unit = details['Price per Unit']
total_price = quantity * price_per_unit
total_amount += total_price
for _ in range(num_items):
item_name = input("Enter the item name: ")
quantity = int(input(f"Enter the quantity for {item_name}: "))
price_per_unit = float(input(f"Enter the price per unit for {item_name}: "))
RESULT:
Thus student marks statement using dictionary in python programming has been executed
successfully.
AIM:
To write a python program using sets to compute intersection, union and difference between
sets.
ALGORITHM:
Step1: Start
Step 2: Input the elements of the first set (set1):
Convert the input string into a set of integers.
Step 3: Input the elements of the second set (set2):
Convert the input string into a set of integers.
Step 4: Compute Intersection:
Find the intersection of set1 and set2 using the & operator.
Store the result in a variable intersection.
Step 5: Compute Union:
Find the union of set1 and set2 using the | operator.
Store the result in a variable union.
Step 6: Compute Symmetric Difference:
Find the symmetric difference of set1 and set2 using the ^ operator.
Store the result in a variable symmetric_difference.
Step 7: Output:
Print the intersection result.
Print the union result.
Print the symmetric_difference result.
Step 8: End
PROGRAM:
def compute_intersection(set1, set2):
# Compute intersection of set1 and set2
return set1 & set2
OUTPUT:
RESULT:
Thus a python program using sets to compute intersection, union and difference between
sets has been executed successfully.
ALGORITHM:
Step 1: Start
Step 2: Define a custom exception InvalidAgeException:
Create a class that inherits from the Exception class.
The constructor should accept a message and pass it to the Exception class.
Step 3: Define the function validate_voter_age(age):
Input: age (the age of the voter).
If age < 18:
Raise an InvalidAgeException with a message "Age is below 18, not eligible
to vote."
Else:
Print "You are eligible to vote."
Step 4: Main program:
Input the user's age and store it in the variable age.
Try block:
Call the function validate_voter_age(age) to validate the age.
Step 5: Exception Handling:
If InvalidAgeException is raised:
Print the error message from the exception (e.message).
If ValueError occurs (non-integer input):
Print "Invalid input! Please enter a valid integer for age."
Step 6: End
PROGRAM:
class InvalidAgeException(Exception):
"""Custom exception for invalid age."""
def __init__(self, message):
self.message = message
super().__init__(self.message)
def validate_voter_age(age):
# Check if the age is valid for voting (18 or older)
if age < 18:
raise InvalidAgeException("Age is below 18, not eligible to vote.")
else:
print("You are eligible to vote.")
# Main program
try:
# Input age from the user
age = int(input("Enter your age: "))
except InvalidAgeException as e:
print(f"Error: {e}")
except ValueError:
print("Invalid input! Please enter a valid integer for age.")
OUTPUT:
Enter your age: 16
Error: Age is below 18, not eligible to vote.
RESULT:
Thus a python program to validate the voter’s age using exception has been executed
successfully.
Ex NO: 12B MARKS RANGE VALIDATION USING EXCEPTION
AIM:
To write a python program to validate the marks using exception.
ALGORITHM:
Step 1: Start
Step 2: Define a custom exception InvalidMarksException:
Create a class InvalidMarksException that inherits from the Exception class.
The constructor should accept a message and pass it to the Exception class.
Step 3: Define the function validate_marks(marks):
Input: marks (integer representing the marks entered by the user).
If marks is less than 0 or greater than 100:
Raise the InvalidMarksException with the message "Marks must be between
0 and 100."
Else:
Print the message marks entered is valid.
Step 4: Main program:
Input: Get the user's marks and store it in the variable marks.
Try block:
Call the validate_marks(marks) function to validate the marks.
Step 5: Exception Handling:
If InvalidMarksException is raised:
Catch the exception and print the error message from the exception.
If ValueError occurs (when the user enters a non-integer value):
Catch the exception and print "Invalid input! Please enter a valid integer for
marks."
Step 6: End
PROGRAM:
class InvalidMarksException(Exception):
"""Custom exception for invalid marks."""
def __init__(self, message):
self.message = message
super().__init__(self.message)
def validate_marks(marks):
# Validate that marks are within the range 0 to 100
if marks < 0 or marks > 100:
raise InvalidMarksException("Marks must be between 0 and 100.")
else:
print(f"Marks entered: {marks} - Valid marks.")
# Main program
try:
# Input marks from the user
marks = int(input("Enter marks: "))
except InvalidMarksException as e:
print(f"Error: {e}")
except ValueError:
print("Invalid input! Please enter a valid integer for marks.")
OUTPUT:
Enter marks: 105
Error: Marks must be between 0 and 100.
Enter marks: 85
RESULT:
Thus a python program to validate the marks using exception has been executed
successfully.
ALGORITHM:
Step 1: Start
Object student1 with specified details (e.g., name, roll number, age, course).
Object student2 with specified details (e.g., name, roll number, age, course).
Step 7: End
PROGRAM:
class Student:
# Constructor to initialize student information
def __init__(self, name, roll_number, age, course):
self.name = name
self.roll_number = roll_number
self.age = age
self.course = course
OUTPUT:
RESULT:
Thus a python program for displaying student information using class and object has been
executed successfully.
ALGORITHM:
Step 1: Start
Step 2: Define the BankAccount class:
Constructor __init__(self, account_holder, balance=0):
Initialize the account holder's name (account_holder).
Initialize the balance (balance) of the account (default is 0).
Step 3: Define the deposit(self, amount) method:
If the amount is greater than 0:
Add amount to the balance.
Print the updated balance.
Else:
Print an error message indicating the deposit amount should be positive.
Step 4: Define the withdraw(self, amount) method:
If the amount is less than or equal to the balance and greater than 0:
Subtract amount from the balance.
Print the updated balance.
Else:
Print an error message indicating insufficient balance or invalid withdrawal
amount.
Step 5: Define the display_account_info(self) method:
Print the account holder's name and current balance.
Step 6: Create an object of the BankAccount class with an initial balance (e.g., account1 =
BankAccount("John Doe", 1000)).
Step 7: Call display_account_info() to show the account details.
Step 8: Perform deposit operation:
Call deposit() with the deposit amount.
Step 9: Perform withdrawal operation:
PROGRAM:
class BankAccount:
# Constructor to initialize account details
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
self.balance = balance
OUTPUT:
RESULT:
Thus a python program for displaying student information using class and object has been
executed successfully.