0% found this document useful (0 votes)
33 views10 pages

Python Programming Lab Manual

The document contains 10 Python programs covering topics like if-else statements, loops, functions, file handling and more. The programs include finding the largest number, checking leap years, calculating grades, validating dates, checking prime numbers, finding LCM and Fibonacci sequences, permutations, set operations and creating a dictionary of word occurrences from a file.

Uploaded by

shyam9.r9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
33 views10 pages

Python Programming Lab Manual

The document contains 10 Python programs covering topics like if-else statements, loops, functions, file handling and more. The programs include finding the largest number, checking leap years, calculating grades, validating dates, checking prime numbers, finding LCM and Fibonacci sequences, permutations, set operations and creating a dictionary of word occurrences from a file.

Uploaded by

shyam9.r9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Course Branch Subject Name with Code Sem

Name
B.Tech CSE ICS-552 Python Programming Lab 5

Program 1: Programs using if else structure.


1) # Python program to find the largest number among the three input numbers

# change the values of num1, num2 and num3


# for a different result
num1 = 10
num2 = 14
num3 = 12

# uncomment following lines to take three numbers from user


#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("The largest number is", largest)


2) # Python program to check if year is a leap year or not

year = 2000
# To get year (integer input) from the user
# year = int(input("Enter a year: "))
# divided by 100 means century year (ending with 00)
# century year divided by 400 is leap year
if (year % 400 == 0) and (year % 100 == 0):
print("{0} is a leap year".format(year))
# not divided by 100 means not a century year
# year divided by 4 is a leap year
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
# if not divided by both 400 (century year) and 4 (not century year)
# year is not leap year
else:
print("{0} is not a leap year".format(year))

3) #Function to calculate grade based on percentage

hindi = int(input("ENTER MARKS OF HINDI: "))


eng = int(input("ENTER MARKS OF ENGLISH: "))
maths = int(input("ENTER MARKS OF MATHS: "))
sci = int(input("ENTER MARKS OF SCIENCE: "))
sst = int(input("ENTER MARKS OF SST: "))

total = hindi+eng+maths+sci+sst

per = total/5

if per >= 90:


grade = 'A'
elif 80 <= per < 90:
grade = 'B'
elif 70 <= per < 80:
grade = 'C'
elif 60 <= per < 70:
grade = 'D'
else:
grade = 'F'

print("The grade is :", grade)

4) #Python Program to Check if a Date is Valid and Print next date


date=input("Enter the date: ")
dd,mm,yy=date.split('/')
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max1=31
elif(mm==4 or mm==6 or mm==9 or mm==11):
max1=30
elif(yy%4==0 and yy%100!=0 or yy%400==0):
max1=29
else:
max1=28
if(mm<1 or mm>12 or dd<1 or dd>max1):
print("Date is invalid.")
elif(dd==max1 and mm!=12):
dd=1
mm=mm+1
print("The incremented date is: ",dd,mm,yy)
elif(dd==31 and mm==12):
dd=1
mm=1
yy=yy+1
print("The incremented date is: ",dd,mm,yy)
else:
dd=dd+1
print("The incremented date is: ",dd,mm,yy)

Program 5: programs using for and while loop


1) #Python program, we will take an input from the user and check whether the number is
prime or not.

num = 10
for i in range (2,num):
if num % i == 0:
print("Not Prime")
break
else:
print("prime")

The entered number is a PRIME number

while loop to check if a number is prime or not in Python:

def is_prime(n):
if n <= 1:
return False
i=2
while i*i <= n:
if n % i == 0:
return False
i += 1
return True

# Test the function


for n in range(2, 10):
print(f"{n}: {is_prime(n)}")

Output: 2: True
3: True
4: False
5: True

6) #Python Program to Find LCM of two numbers

num1 = 12
num2 = 14
for i in range(max(num1, num2), 1 + (num1 * num2), max(num1, num2)):
if i % num1 == i % num2 == 0:
lcm = i
break
print("LCM of", num1, "and", num2, "is", lcm)
Output
LCM of 12 and 14 is 84

7) #Python Program to Find the Sum of Digits in a Number


num = input("Enter Number: ")
sum = 0

for i in num:
sum = sum + int(i)

print(sum)

8) # Python program to display the Fibonacci sequence

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))

9. ) # Write a Python program to display all the permutations of given string (don’t use
python permutation function)

def get_permutation(string, i=0):

if i == len(string):
print("".join(string))
for j in range(i, len(string)):

words = [c for c in string]

# swap
words[i], words[j] = words[j], words[i]

get_permutation(words, i + 1)

print(get_permutation('yup'))

9) # Consider a scenario from SVU. Given below are two Sets representing the names
of students enrolled for a particular course: java course = {"Anmol", "Rahul",
"Priyanka", "Pratik"} python course = {"Rahul", "Ram", "Nazim", "Vishal"}
Write a Python program to list the number of students enrolled for:
1. Python course
2. Java course only
3. Python course only
4. Both Java and Python courses
5. Either Java or Python courses but not both
6. Either Java or Python

# Given Sets
java_course = {"Anmol", "Rahul", "Priyanka", "Pratik"}
python_course = {"Rahul", "Ram", "Nazim", "Vishal"}

# 1. Number of students enrolled for Python course


num_python_students = len(python_course)
print("Number of students enrolled for Python course:", num_python_students)

# 2. Students enrolled for Java course only


java_only_students = java_course - python_course
print("Students enrolled for Java course only:", java_only_students)

# 3. Students enrolled for Python course only


python_only_students = python_course - java_course
print("Students enrolled for Python course only:", python_only_students)
# 4. Students enrolled for Both Java and Python courses
both_courses_students = java_course & python_course
print("Students enrolled for Both Java and Python courses:", both_courses_students)

# 5. Students enrolled for Either Java or Python courses but not both
either_course_not_both_students = (java_course | python_course) - both_courses_students
print("Students enrolled for Either Java or Python courses but not both:",
either_course_not_both_students)

# 6. Students enrolled for Either Java or Python courses


either_course_students = java_course ^ python_course
print("Students enrolled for Either Java or Python courses:", either_course_students)

10) # Function with Keyword and Default Arguments


def greet(name, greeting="Hello", punctuation="!"):
"""
This function greets a person with a custom message.

Parameters:
- name: The name of the person to greet.
- greeting: The greeting message (default is "Hello").
- punctuation: The punctuation at the end of the greeting (default is "!").

Returns:
A formatted greeting message.
"""
return f"{greeting}, {name}{punctuation}"

# Program using the functions


def main():
# Example 1: Using only positional arguments
print(greet("Alice"))

# Example 2: Using keyword arguments


print(greet(name="Bob", greeting="Hi"))

# Example 3: Using default values for some arguments


print(greet("Charlie", punctuation="."))

# Example 4: Mixing positional, keyword, and default arguments


print(greet("David", greeting="Hey", punctuation="?"))

if __name__ == "__main__":
main()
11.) #Write a python program to write few lines on a file, read it back and create a
dictionary having each word in file as keys in dictionary and occurrence of these
word as values and print the dictionary.

def write_lines_to_file(file_path, lines):


"""Write lines to a file."""
with open(file_path, 'w') as file:
for line in lines:
file.write(line + '\n')

def create_word_occurrence_dictionary(file_path):
"""Read lines from a file, create a dictionary with word occurrences."""
word_occurrences = {}
with open(file_path, 'r') as file:
for line in file:
words = line.split()
for word in words:
# Remove punctuation and convert to lowercase for simplicity
word = word.strip('.,?!:;\'"()[]{}').lower()
word_occurrences[word] = word_occurrences.get(word, 0) + 1
return word_occurrences

def main():
# Write lines to a file
lines_to_write = [
"This is a sample line.",
"Another line with some words.",
"Sample line for word occurrence dictionary."
]
file_path = "sample_file.txt"
write_lines_to_file(file_path, lines_to_write)

# Read lines from the file and create a word occurrence dictionary
word_occurrences = create_word_occurrence_dictionary(file_path)

# Print the word occurrence dictionary


print("Word Occurrence Dictionary:")
for word, count in word_occurrences.items():
print(f"{word}: {count}")

if __name__ == "__main__":
main()

You might also like