Python Exercises
Python Exercises
1. Write a Program that swaps the values of two variables given as input by the user.
and Surface Area of the sphere. (Use the value of 𝜋 i.e. 3.142, as a constant. Volume of a
2. Write a program that asks the user for the diameter of a sphere and then computes the Volume
Strings
23. Consider the string text = "Python programming is fun, isn't it?". Use string methods to replace
all instances of 'is' with 'should be' and then find the position of the first occurrence of 'fun' in
the modified string.
24. Given a string phrase = "PyTHoN iS AwEsOmE", convert the string so that the first letter is
uppercase and the rest of the characters are lowercase. What is the resulting string?
25. You have a string data = "name:John Doe;age:30;profession:Software Engineer". Split this string
into individual components based on the semicolon (;) and then create a list where each
element is a key-value pair (as a string) derived from the components. Finally, join these key-
value pairs using a comma and a space. What is the final string?
26. Given a multiline string paragraph = """Python is an interpreted, high-level and general-purpose
programming language. Python's design philosophy emphasizes code readability with its
notable use of significant whitespace.""", count how many times the substring 'Python' (case-
sensitive) appears in paragraph.
27. Ask the user to input a word, and write a Python program to check if the word is a palindrome.
A palindrome is a word that reads the same backward as forward, e.g., "racecar". Ignore case
sensitivity and spaces.
28. Write a Python program that asks the user for their email address and then extracts and prints
the domain of the email address. For example, if the input is "[email protected]", the output
should be "example.com".
29. Ask the user to input a string and write a Python program to count how many vowels (a, e, i, o,
u) are in the string. Use string methods and consider both uppercase and lowercase vowels. For
example, if the input is "Hello World", the output should be 3.
30. Write a Python program that takes a sentence from the user and reverses the order of the
words in the sentence. Use string methods to accomplish this. For example, if the input is
"Python is easy to learn", the output should be "learn to easy is Python".
Lists
31. Create a list of your five favorite fruits. Use the append() method to add another fruit to the list,
and then use the remove() method to remove one fruit from the list. Print the final list.
32. Create a list of your 7 favorite movies and print the third movie on the list.
33. Combine two lists into a single list without using the + operator.
34. Given a list of colors: ["red", "blue", "green", "yellow", "purple"], write a Python script that
inserts "orange" after "green" and removes "yellow". Print the final list of colors.
35. Create a list of pet names. Write a script that asks the user for a pet name and removes that pet
name from the list if it exists. If the pet name does not exist in the list, print an appropriate
message.
36. Write a program that asks the user to enter three favorite colors, one by one. Store these colors
in a list. Then, print the first and last color entered.
37. Ask the user to create a list of four numbers by entering them one at a time. After the list is
created, ask the user for a number to add to the list, but they must also specify the position
(index) in the list where this new number should be placed, replacing the existing number at
that position. Print the updated list.
38. Create a program where the user enters five movie names to store in a list. After the list is
created, ask the user for a movie name to remove from the list. Remove the movie by directly
specifying its value (not by index, since you haven't learned loops for finding indexes). Print the
updated list.
39. Write a program that starts with a list of two items: ["Hello", "World"]. Ask the user to add
three more words to the list, entering them one at a time. After adding each word, print the
current state of the list.
40. Ask the user to enter their top three hobbies and then their top three foods. Store these in two
separate lists. Then, create a nested list that contains both lists and print it. Finally, ask the user
to select a number: 1 for hobbies or 2 for foods. Based on their choice, print the corresponding
list from the nested list.
Loops:
Functions
57. Write a function to calculate the factorial of a number. Use recursion to solve the problem.
58. Create a function that checks if a given word is a palindrome. The function should return True if
it is a palindrome, otherwise False.
59. Develop a function that converts temperature from Celsius to Fahrenheit and vice versa. The
function should accept two parameters: the temperature value and the unit to convert to.
60. Write a function to count the number of vowels in a given string. Use the string as a parameter
for the function.
61. Create a function that returns the nth Fibonacci number. Use recursion or iteration based on
your preference.
62. Develop a function that accepts a list of numbers and returns a new list with the even numbers
only.
63. Create a function that takes a list of words and returns the longest word and its length.
64. Write a function that accepts a list of strings and returns a dictionary with the strings as the keys
and their lengths as the values.
65. Create a function that accepts a string and returns a new string where every character in the
original is repeated twice (e.g “Help” “HHeellpp”).
66. Write a function that checks if a given year is a leap year. The function should return True for
leap years and False otherwise.
67. Write a function that accepts two lists and returns a new list that contains only the elements
that are common between the lists (without duplicates).
Files:
68. Write a Python program that reads a file's content and writes its content back to another file in
reverse order. For example, if the original file has lines 1, 2, and 3, the new file should have lines
3, 2, and 1.
69. Create a function that takes a filename as input and counts the number of words in that file.
Consider that words are separated by whitespace.
70. Write a program that reads text from a file and prints a list of unique words, sorted
alphabetically. Ensure the program is case-insensitive and strips punctuation.
71. Write a Python program that reads a file and writes another file that is identical but prefixes
each line with a line number followed by a colon. For example, "Hello World" becomes "1: Hello
World".
Error Handling:
72. Create a function that accepts two numbers as input and divides them. Use error handling to
catch division by zero errors and print a friendly error message instead of crashing the program.
73. Write a program that prompts the user to enter a filename and then attempts to open it and
print its contents to the console. Use error handling to catch and inform the user if the file
doesn't exist.
74. Suppose you have a list of strings representing integers e.g., ['2', '5', '29', 'a', '7']. Write a
program that converts each string to an integer and calculates the sum of all numbers. Use
error handling to skip any values that cannot be converted to integers.
75. Write a Python program that tries to write data to a file and ensures that the file stream is
properly closed even if an error occurs during the write operation. Use try, except, and finally
blocks to demonstrate resource cleanup.