0% found this document useful (0 votes)
43 views16 pages

Python Programs for Common Tasks

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)
43 views16 pages

Python Programs for Common Tasks

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

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 = [Link]()
lengths = []
for word in words:
[Link](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 [Link]():
if [Link](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 [Link]():
if marks > 75:
[Link](name)

def pop(stk):
if stk:
while stk:
print([Link](), 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 [Link]():
if marks > 80:
[Link]((name, marks))
def pop_and_display(stk):
if stk:
while stk:
name, marks = [Link]()
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:
[Link](num)

def pop_even():
global EvenNumbers
if EvenNumbers:
return [Link]()
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:
[Link]([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:
[Link]([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, [Link] 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 [Link]('You'):
print(line, end='')
[Link]()
except FileNotFoundError:
print("The file does not exist.")

display_you_lines('[Link]')
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 [Link].
the contents of the [Link] 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
[Link]()
print("Number of vowels:", count)
except FileNotFoundError:
print("The file does not exist.")

vowelCount('[Link]')

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 [Link]. The program should:
(i) Create the file [Link] (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('[Link]', mode='w',
newline='')
writer = [Link](file)
header = ['Serial No', 'Name', 'Date of Birth']
[Link](header)
sr = input("Enter Serial Number: ")
name = input("Enter Name: ")
dob = input("Enter DOB(dd/mm/yyyy): ")
[Link]([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 [Link]
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 [Link] 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('[Link]', mode='r') as file:
reader = [Link](file)
next(reader) # Skip the header row
for row in reader:
dob = row[2]
year = int([Link]('/')[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, [Link], containing records of the following


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

for line in infile:


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

[Link]()
[Link]()

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

output:
Total records copied: 2

Common questions

Powered by AI

To count vowels, define a string containing all vowels, both uppercase and lowercase. Iterate through each character of the input string and check if it exists in the vowel string. If it does, increment a counter. After the iteration is complete, the counter reflects the total number of vowels in the string .

To manage even integers with a stack, iterate through the list checking each integer for evenness (divisibility by 2). Those that are even are pushed onto a global stack. Pop operations are used to remove and retrieve the top element, displaying or returning it from the stack when required. This approach enables dynamic stack content management and is structured with functions for clarity .

The algorithm initializes two variables, `i` and `fact`, starting with 1. It then iteratively multiplies `fact` by `i` and increments `i` until `fact` is equal to or exceeds the number being checked. If `fact` equals the original number at any point, the number is a factorial; otherwise, it is not .

To filter cities, iterate through a nested list and check each record against the specified conditions (Country not 'India' and Distance < 3500 km). If a record meets the criteria, push a list containing the city and country onto a predefined stack. This method involves both data checking and stack operations .

Book records are filtered by iterating over a nested list and checking each book's genre and price. If the book meets the criteria ('Fiction' genre and price < 500), its title and author are pushed onto a stack. Stack operations then include these filtered records managed by functions that facilitate additions and display logic without removing stack entries .

You can filter 'IT' department employees by iterating through the list of employee records and checking the department of each employee. If the department matches 'IT', add that employee's record to a new list. This approach uses a for loop to check and append conditionally .

To check if a number is a palindrome, you reverse its digits and compare the reversed number to the original. If they are the same, the number is a palindrome. The reversal process involves extracting the last digit of the number iteratively and forming the reversed number .

To generate a Fibonacci series, initialize the first two terms as 0 and 1. Then, in a loop, print the current term, update the next term by summing the current term and the previous term, and then update the current term to the next term. Repeat this process until the desired number of terms, 'n', is reached .

A year is a leap year if it is divisible by 4. However, if the year is divisible by 100, it is not a leap year unless it is also divisible by 400. This means you first check if the year is divisible by 4, then check if it is divisible by 100 and only continues with the leap year status if it is also divisible by 400 .

To write student records to a CSV file, you open the file in write mode and use a CSV writer to add headers and entries to the file, taking input for each field. To read, open the file in read mode and use a CSV reader to iterate through the lines, skipping the header row and processing data as needed. This involves handling file streams and using Python's CSV module .

You might also like