Practical File- 20 codes
Practical File- 20 codes
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
else:
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Output:
Enter a year: 2024
2024 is a leap year.
if fact == num:
print(num, "is a factorial of some integer.")
else:
print(num, "is not a factorial of any integer.")
Output:
Enter a number: 120
120 is a factorial of some integer.
Enter a number: 100
100 is not a factorial of any integer.
if original_num == reverse_num:
print(original_num, "is a palindrome.")
else:
print(original_num, "is not a palindrome.")
Output:
Enter an integer: 121
121 is a palindrome.
print("Fibonacci sequence:")
while count < n:
print(a)
a, b = b, a + b
count += 1
Output:
Enter the number of terms: 8
Fibonacci sequence:
0
1
1
2
3
5
8
13
Output:
Enter a string: Hello World
Number of vowels: 3
7. Write a Python function to filter out and print only the records of
employees who work in the "IT" department from a nested list of
employee records. Each employee's record is stored as a sublist
containing the employee's name, age, and department.
def filter_emp(employees):
it_employees = []
for employee in employees:
if employee[2] == "IT":
it_employees.append(employee)
return it_employees
employee_records = [
["John", 28, "HR"],
["Sarah", 34, "IT"],
["Alex", 25, "IT"],
["Emily", 30, "Marketing"],
["Daniel", 29, "IT"]
]
it_employees = filter_emp(employee_records)
print("Employees working in IT:")
for employee in it_employees:
print(employee)
Output:
Employees working in IT:
['Sarah', 34, 'IT']
['Alex', 25, 'IT']
['Daniel', 29, 'IT']
8. Write a Python function that takes a string as input and returns a list
containing the length of each word in the string. The string will be
split into words by spaces.
def word_lengths(s):
words = s.split()
lengths = []
for word in words:
lengths.append(len(word))
return lengths
Output:
Enter a string: Hello world this is Python
The lengths of each word: [5, 5, 4, 2, 6]
9. Write a Python function that takes a list with repeated values and
returns a new list containing only the unique elements (i.e., no
duplicates).
def unique_elements(lst):
unique_lst = []
for item in lst:
if item not in unique_lst:
unique_lst.append(item)
return unique_lst
numbers = [1, 2, 3, 2, 4, 5, 1, 6, 3]
unq_num = unique_elements(numbers)
print("List with unique elements:",unq_num)
Output:
List with unique elements: [1, 2, 3, 4, 5, 6]
10. Write a Python function that takes a dictionary where the keys are
countries and the values are their respective capitals. The function
should return a dictionary with the countries and capitals that start
with a specific letter (provided by the user).
def filter_cap(countries, letter):
result = {}
for country, capital in countries.items():
if capital.startswith(letter):
result[country] = capital
return result
cou_n_cap = {
"India": "New Delhi",
"USA": "Washington, D.C.",
"Canada": "Ottawa",
"Australia": "Canberra",
"Brazil": "Brasília",
"Germany": "Berlin"
}
Output:
Enter the letter to filter capitals: B
Countries and their capitals starting with B : {'Brazil': 'Brasília',
'Germany': 'Berlin'}
11. Julie has created a dictionary containing names and marks as key
value pair of 6 students. Write a program, with separate user defined
functions to perform the following operations.
(a) Push(R, stk): Push the keys (name of the student) of the
dictionary into a stack. Where the corresponding value (marks)
is greater than 75.
(b) Pop(stk): pop and display the content of the stack. Also print “
Stack Empty” when stack is empty.
For example if the sample content of the dictionary is as follows
R = {“OM”:76, ”JAI”: 45, “BOB”: 89, “ANU”:90, “TOM”:82}
The output from the program should be
TOM ANU BOB OM
def pop(stk):
if stk:
while stk:
print(stk.pop(), end=" ")
else:
print("Stack Empty")
R = {
"OM": 76,
"JAI": 45,
"BOB": 89,
"ANU": 90,
"TOM": 82
}
stk = []
push(R, stk)
pop(stk)
Output:
TOM ANU BOB OM
12. Julie has created a dictionary containing names and marks as key-
value pairs of students. Write a program to perform the following
operations:
(a) Push the names of students who scored more than 80 into a
stack.
(b) Pop the stack and print each student's name along with their
score.
For example, given the dictionary:
R = {"Alice": 75, "Bob": 82, "Charlie": 95, "Daisy": 89, "Eva": 60}
R = {
"Alice": 75,
"Bob": 82,
"Charlie": 95,
"Daisy": 89,
"Eva": 60
}
stk = []
push_high_achievers(R, stk)
pop_and_display(stk)
Output:
Daisy 89
Charlie 95
Bob 82
def pop_even():
global EvenNumbers
if EvenNumbers:
return EvenNumbers.pop()
else:
return "Empty"
def disp_even():
global EvenNumbers
if EvenNumbers:
print("Stack contents:", EvenNumbers)
else:
print("None")
print(pop_even())
print(pop_even())
print(pop_even())
disp_even()
Output
Stack contents: [10, 20, 30]
30
Stack contents: [10, 20]
20
20
10
Empty
None
14. A nested list, NList, contains records where each element is a list in
the format:
[City, Country, Distance from Delhi].
Write a user-defined function Push_element(NList) in Python to
perform operations on a stack named travel. The function should
take the nested list NList as its argument and push a list containing
the City and Country onto the stack travel for all records where the
Country is not India and the Distance from Delhi is less than 3500
km.
travel = []
def Push_element(NList):
global travel
for record in NList:
if record[1] != "India" and record[2] <
3500:
travel.append([record[0], record[1]])
NList = [
["Dubai", "UAE", 2200],
["Mumbai", "India", 1400],
["Kathmandu", "Nepal", 1200],
["Singapore", "Singapore", 4100],
["Colombo", "Sri Lanka", 2400]
]
Push_element(NList)
print("Stack contents:")
for record in travel:
print(record)
Output:
Stack contents:
['Dubai', 'UAE']
['Kathmandu', 'Nepal']
['Colombo', 'Sri Lanka']
15. A nested list, BookList, contains records where each element is a list
in the format:
[BookTitle, Author, Genre, Price].
Write a user-defined function Push_books(BookList) in Python to
perform operations on a stack named BooksStack. The function
should take the nested list BookList as its argument and push a list
containing the BookTitle and Author onto the stack BooksStack for
all books where:
(i) The Genre is "Fiction", and
(ii) The Price is less than 500.
Write code to display the contents of the stack line by line. If the
stack is empty, display "No books available".
BooksStack = []
def Push_books(BookList):
global BooksStack
for record in BookList:
if record[2] == "Fiction" and record[3] < 500:
BooksStack.append([record[0], record[1]])
def display_stack():
if BooksStack:
for record in BooksStack:
print(record)
else:
print("No books available")
BookList = [
["The Alchemist", "Paulo Coelho", "Fiction", 350],
["Sapiens", "Yuval Noah Harari", "Non-Fiction", 600],
["The Great Gatsby", "F. Scott Fitzgerald", "Fiction", 450],
["1984", "George Orwell", "Fiction", 550],
["To Kill a Mockingbird", "Harper Lee", "Fiction", 250]
]
Push_books(BookList)
display_stack()
Output:
['The Alchemist', 'Paulo Coelho']
['The Great Gatsby', 'F. Scott Fitzgerald']
['To Kill a Mockingbird', 'Harper Lee']
16. Write a function in Python to read a text file, Alpha.txt and displays
those lines which begin with the word „You‟.
the content of text file are:
You are my sunshine.
This is a test line.
You should not forget this.
You have the potential to succeed.
def display_you_lines(filename):
try:
file = open(filename, 'r')
for line in file:
if line.startswith('You'):
print(line, end='')
file.close()
except FileNotFoundError:
print("The file does not exist.")
display_you_lines('Alpha.txt')
Output:
You are my sunshine.
You should not forget this.
You have the potential to succeed.
17. Write a function, vowelCount() in Python that counts and displays
the number of vowels in the text file named Poem.txt.
the contents of the peom.txt are:
The sky is blue,
The grass is green,
Birds fly high in the sky.
def vowelCount(filename):
try:
file = open(filename, 'r')
vowels = 'aeiouAEIOU'
count = 0
for line in file:
for char in line:
if char in vowels:
count += 1
file.close()
print("Number of vowels:", count)
except FileNotFoundError:
print("The file does not exist.")
vowelCount('Poem.txt')
Output:
Number of vowels: 18
18. Write a Python program to take input of the serial number, name,
and date of birth of a student, and save the details into a CSV file
named students.csv. The program should:
(i) Create the file students.csv (if it doesn‟t exist).
(ii) Write a header row with the following columns: Serial No,
Name, Date of Birth.
(iii) Prompt the user to enter the serial number, name, and date of
birth for the student.
(iv) Save the entered data as a new row in the CSV file.
import csv
def save_student_data():
file = open('students.csv', mode='w',
newline='')
writer = csv.writer(file)
header = ['Serial No', 'Name', 'Date of Birth']
writer.writerow(header)
sr = input("Enter Serial Number: ")
name = input("Enter Name: ")
dob = input("Enter DOB(dd/mm/yyyy): ")
writer.writerow([sr, name, dob])
print("Student data saved successfully.")
save_student_data()
Output:
Enter Serial Number: 1
Enter Name: John Doe
Enter DOB(dd/mm/yyyy): 15/03/2005
19. Write a Python program that reads a CSV file named students.csv
and displays the details of students who were born after the year
2000. The CSV file contains the following columns: Serial No, Name,
and Date of Birth (in the format dd/mm/yyyy).
the content of the students.csv are:
Serial No, Name, Date of Birth
1, John Doe, 15/03/2005
2, Jane Smith, 23/06/1999
3, Mark Lee, 12/12/2002
4, Sarah Lee, 01/01/1998
import csv
def display_students_born_after_2000():
with open('students.csv', mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
dob = row[2]
year = int(dob.split('/')[2])
display_students_born_after_2000()
Output:
Serial No: 1, Name: John Doe, Date of Birth: 15/03/2005
Serial No: 3, Name: Mark Lee, Date of Birth: 12/12/2002
infile.close()
outfile.close()
return records_copied
records = copyData()
print("Total records copied:", records)
output:
Total records copied: 2