0% found this document useful (0 votes)
8 views

Practical File- 20 codes

The document contains a series of Python programming tasks that include checking for leap years, determining factorials, identifying palindromes, generating prime numbers, creating Fibonacci sequences, counting vowels, filtering employee records, and manipulating stacks with various data structures. Each task is accompanied by code snippets and example outputs to demonstrate functionality. The tasks cover a wide range of programming concepts suitable for beginners to intermediate learners.

Uploaded by

Himanshu Tonk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Practical File- 20 codes

The document contains a series of Python programming tasks that include checking for leap years, determining factorials, identifying palindromes, generating prime numbers, creating Fibonacci sequences, counting vowels, filtering employee records, and manipulating stacks with various data structures. Each task is accompanied by code snippets and example outputs to demonstrate functionality. The tasks cover a wide range of programming concepts suitable for beginners to intermediate learners.

Uploaded by

Himanshu Tonk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1. Write a Python program to check if a given year is a leap year or not.

year = int(input("Enter a year: "))

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.

Enter a year: 1900


1900 is not a leap year.

2. Write a Python program to check if a given number is a factorial of


some integer.
num = int(input("Enter a number: "))
i = 1
fact = 1

while fact < num:


i += 1
fact *= i

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.

3. Write a Python program to check if a given integer is a palindrome.


A number is a palindrome if it reads the same forwards and
backwards.
num = int(input("Enter an integer: "))
original_num = num
reverse_num = 0

while num > 0:


digit = num % 10
reverse_num = reverse_num * 10 + digit
num = num // 10

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.

Enter an integer: 123


123 is not a palindrome.

4. Write a Python program to print all the prime numbers within a


given range. The range should be provided by the user.
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

# Printing the prime numbers within the range


print("Prime numbers between", start, "and", end,
"are:")

for num in range(start, end + 1):


if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
print(num)
Output:
Enter the starting number: 10
Enter the ending number: 30
Prime numbers between 10 and 30 are:
11
13
17
19
23
29
5. Write a Python program to generate the Fibonacci series up to n
terms, where n is input by the user.
n = int(input("Enter the number of terms: "))
a, b = 0, 1
count = 0

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

6. Write a Python function to count the number of vowels in a given


string.
def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count

string = input("Enter a string: ")


print("Number of vowels:", count_vowels(string))

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

input_string = input("Enter a string: ")


print("The lengths of each word:",
word_lengths(input_string))

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"
}

letter = input("Enter the letter : ")


filter_data = filter_cap(cou_n_cap, letter)
print("Countries and their capitals starting with",
letter, ":", filter_data)

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 push(R, stk):


for name, marks in R.items():
if marks > 75:
stk.append(name)

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}

def push_high_achievers(R, stk):


for name, marks in R.items():
if marks > 80:
stk.append((name, marks))
def pop_and_display(stk):
if stk:
while stk:
name, marks = stk.pop()
print(name, marks)
else:
print("Stack Empty")

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

13. Write the definition of a user-defined function push_even(N) which


accepts a list of integers in a parameter N and pushes all those
integers which are even from the list N into a Stack named
EvenNumbers.
Write function pop_even() to pop the topmost number from the stack
and returns it. If the stack is already empty, the function should
display "Empty".
Write function Disp_even() to display all element of the stack
without deleting them. If the stack is empty, the function should
display 'None'.
EvenNumbers = []
def push_even(N):
global EvenNumbers
for num in N:
if num % 2 == 0:
EvenNumbers.append(num)

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")

nums = [10, 15, 20, 25, 30]


push_even(nums)
disp_even()
print(pop_even())
disp_even()

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])

if year > 2000:


print(f"Serial No:” {row[0]}, Name:
{row[1]}, Date of Birth: {dob}")

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

20. Consider a file, SPORT.DAT, containing records of the following


structure:
[SportName, TeamName, No_Players]
Write a function, copyData(), that reads contents from the file
SPORT.DAT and copies the records with Sport name as “Basket
Ball” to the file named BASKET.DAT. The function should return
the total number of records copied to the file BASKET.DAT.
def copyData():
records_copied = 0
infile = open('SPORT.DAT', 'r')
outfile = open('BASKET.DAT', 'w')

for line in infile:


parts = line.strip().split(', ')
if parts[0] == "Basket Ball":
outfile.write(line)
records_copied += 1

infile.close()
outfile.close()

return records_copied
records = copyData()
print("Total records copied:", records)

output:
Total records copied: 2

You might also like