0% found this document useful (0 votes)
11 views5 pages

Python Exercises

Python exercises CS306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

Python Exercises

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

Python Exercises

Arithmetic and conditions:

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

sphere = 4/3 𝜋𝑟**3 , Surface Area = 4𝜋𝑟**2 )


3. Write a program that takes three numbers x,y,z as input and calculate and print
x+y+z
x-y-z
y-x-z
z-x-y
x*y*z
x/y*z
x*y/z
x/y/z
x%y
y%z
z%x
z**y
z//y//x
y//x
z//x
4. Given two variables a = 10 and b = 5, perform the following operations:
Addition of a and b and store it in a
Subtraction of b from a store it in b
Multiplication of a and b and store it in a
Division of a by b and store it in b
Exponentiation (a to the power of b)
5. Write a program that takes a number x as input and prints True if x is even.
6. Write a program that takes two numbers x and y as input and prints True if x is a multiple of y.
7. Write a program that compares two strings entered by the user (str1 and str2) and prints
whether they are equal or not.
8. Given two variables entered by the user (a and b), write a program that prints True if a is
greater than b, else prints False.
9. Given three variables (num1, num2, and num3) entered by the user, write a program that
checks if:
num1 < num2 and num2 >= num3
num1 > num2 or num1 >num3
num2 >= num1 and num1 != num3
and prints the appropriate result.
10. You have 100 rupees to buy a ticket of movie. Each ticket costs 12 rupees. Write a Python
program to calculate how many tickets you can buy.
11. In the last three cricket games, Babar Azam scored 22, 28, and 35 . write a Python program to
calculate his average score per game.
12. You're building a rectangular garden that's 20 meters long and 15 meters wide. Calculate the
total length of fencing needed to enclose the garden and print the answer.
13. If each pizza can serve 3 people, write a program to find out how many pizzas are needed for a
party of 27 people.
14. If your bike uses 3 liters of fuel per 100 km and fuel costs 270 rupees per liter, how much will
the fuel cost for a 400 km trip? Write a Python program to calculate the cost.
15. Write a Python program that asks the user to enter a number. The program should then use an
if-else statement to print whether the number is even or odd.
16. Ask the user to input two numbers. Use an if-else statement to determine which number is
larger, or if they are equal, and print an appropriate message for each case.
17. Write a program where a user enters a number. Use an if-else structure to check whether the
number is positive, negative, or zero and print the result.
18. Ask the user to input a year. Use an if-else statement to determine if the year is a leap year or
not. A year is a leap year if it is divisible by 4, except for years which are divisible by 100 unless
they are also divisible by 400.
19. Write a Python program that categorizes a person's age into 'Child' (< 13), 'Teen' (13-19), 'Adult'
(20-59), and 'Senior' (60 and above) using only if-else statements (no elif allowed).
20. Write a program that simulates a traffic light. The user enters a color ('red', 'yellow', 'green'),
and the program prints 'Stop' for red, 'Caution' for yellow, and 'Go' for green using only if-else
statements.
21. Write a program that converts a temperature from Fahrenheit to Celsius. Classify the
temperature as 'Freezing' (< 0°C), 'Cold' (0-15°C), 'Moderate' (15-25°C), 'Warm' (25-35°C), and
'Hot' (>35°C) using only if-else statements.
22. Write a Python program that categorizes a student's mark (0-100) into 'A' (90-100), 'B' (80-89),
'C' (70-79), 'D' (60-69), and 'F' (below 60) using only if-else statements.

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:

41. Print numbers from 1 to 10 using a while loop.


42. Ask the user for a number n and then calculate the sum of the first n natural numbers.
43. Ask the user for a number n and print all even numbers less than n.
44. Calculate the factorial of a given number n provided by the user.
45. Ask the user for the base x and exponent n and calculate x raised to the power n
46. Ask the user to input a number and print all divisors of that number.
47. Ask the user to enter a negative number and keep asking until a positive number is entered.
Then, print the positive number.
48. Ask the user for a number n and print numbers from n down to 1.
49. Keep asking the user to enter a number until they enter 0. Print the sum of all entered numbers.
50. Ask the user to enter a number, then print the multiplication table for that number up to 10.
51. Ask the user for a string and use a for loop to reverse it.
52. Ask the user to input a number and use a for loop to count the number of digits in that number.
53. Given a list of numbers, use a for loop to calculate the average.
54. Given a list of strings, use a for loop to concatenate all elements into a single string.
55. Given a string, use a for loop to iterate through each character and break the loop when the
first non-alphabetic character is encountered. Print the position of this character.
56. Given a list of words, use a for loop to print each word until you encounter the word "stop".
Once "stop" is encountered, exit the loop.

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.

You might also like