Python Exercises
Python Exercises
7
4. Format String with Variables
Given name = "Alice" and age = 30, use f-strings to print the sentence:
"Alice is 30 years old."
5. Repeat a String Multiple Times
11 Given word = "ha", print it three times in a row to produce "hahaha".
6. Convert String to Uppercase
Given text = "hello world", print the string in all uppercase letters.
7. Print String in Title Case
Given title = "the great gatsby", print the title in title case (each word
capitalized).
8. Print the Length of a String
Given sentence = "Hello, Python!", print the length of the string.
TG
7
20. Convert CamelCase to Snake_Case
Given camel_case = "CamelCaseExample", convert it to snake_case
("camel_case_example") and print the result.
11
Basic Exercises Variables and Printing
Intermediate Exercises
7
Ask the user for hours and minutes, then calculate the total number of minutes and
print the result.
13. Split Bill Among Friends
Take inputs for total bill amount and number of people. Calculate and print the
amount each person should pay (divide total by number of people, rounded to two
11decimal places).
14. Calculate Compound Interest
Take inputs for principal, rate, time, and number of times interest applied per time
period (n). Calculate compound interest using the formula A = P * (1 +
R/n)^(n*T) and print the result.
15. Distance Between Two Points
Take inputs for two points (x1, y1) and (x2, y2), then calculate the distance
TG
Print the following text with each item on a new line using `\n`:
7
Shopping List:
- Apples
- Bananas
- Oranges
11
3. Tab Escape Sequence
Format and print the following items with tab spaces between them:
4. Backslash in a String
Use the carriage return escape sequence `\r` to print the following output:
`Starting... Overwritten`
Op : Overwritten
Use the backspace escape sequence `\b` to print the word `Hell` by typing `Hello` in
the code and removing the last character.
Print a string that uses the form feed escape sequence `\f` to separate two
paragraphs. The output should look like there is a gap between the paragraphs:
7
First Paragraph\fSecond Paragraph
11
9. Octal and Hexadecimal Escape Sequence
Print the letters `A`, `B`, and `C` using their octal (`\101`, `\102`, `\103`) and
hexadecimal (`\x41`, `\x42`, `\x43`) escape codes.
Languages:
- Python
- Java
- JavaScript
List Exercises
1. Create an empty list and add the numbers 1, 2, 3, and 4 to the list using the append()
method.
2. Given a list colors = ["red", "blue", "green"], add the color "yellow" to the
end of the list using append().
3. Using the list fruits = ["apple", "banana", "mango"], add "orange" to the list
at index 1 using the insert() method.
4. Start with a list numbers = [1, 3, 5, 7]. Add the number 9 at index 4 using the
insert() method.
5. Create a list letters = ["a", "c", "d"]. Add the letter "b" at index 1 using
7
insert() to make the list alphabetically ordered.
6. You have a list names = ["John", "Alice"]. Add two names "Mike" and "Eva" to
the list at once using extend().
11
7. Given the list numbers = [10, 20, 30], add the value 25 between 20 and 30 using
the insert() method.
8. Create a list cities = ["New York", "London"]. Add the cities "Paris" and "Tokyo"
to the list using append() for each.
TG
9. Given a list animals = ["cat", "dog", "rabbit"], add the animal "elephant" at
index 2 using insert().
10. You have the list scores = [85, 90, 95]. Add the score 100 at the end of the list
using append(), and then add the score 80 at the beginning using insert().
List Slicing
Exercise 1:
Given a list numbers = [10, 20, 30, 40, 50, 60], slice the list to extract the sublist
[20, 30, 40].
Exercise 2:
You have a list letters = ['a', 'b', 'd', 'e']. Insert the letter 'c' at the correct
position using list slicing to create a new alphabetically ordered list.
Exercise 3:
7
reverse the list and assign the reversed list to a new variable.
Exercise 4:
11
Start with two lists: list1 = [1, 2, 3] and list2 = [4, 5, 6]. Use the extend()
method to combine both lists into a single list.
Exercise 5:
Given a list nums = [10, 20, 30, 40, 50], remove the last two elements using slicing,
and store the resulting list in a new variable.
TG
Exercise 6:
You have the list colors = ["red", "blue", "green"]. Add "yellow" and "purple" at
the end of the list using the extend() method.
Exercise 7:
Create a list letters = ['a', 'b', 'c', 'e', 'f']. Use slicing to replace 'e' and 'f'
with 'd', so the final list becomes ['a', 'b', 'c', 'd'].
Exercise 8:
Given a list numbers = [10, 20, 30, 40, 50], insert [60, 70, 80] after the
element 30 using slicing and extend().
Exercise 9:
You have a list names = ["Alice", "Bob", "Charlie", "Eva"]. Extract a sublist
containing only the second and third names using slicing.
Exercise 10:
Exercise 1:
Given a list numbers = [10, 20, 30, 40, 50], remove the number 30 using the
remove() method.
7
Exercise 2:
You have the list fruits = ["apple", "banana", "cherry", "date", "fig"].
11
Remove the last element from the list using the pop() method and store the popped
element in a new variable.
Exercise 3:
Given the list letters = ['a', 'b', 'c', 'd', 'e'], remove the element at index
1 using the del statement.
TG
Exercise 4:
Create a list colors = ["red", "green", "blue", "yellow"]. Remove the first
element from the list using pop() with the appropriate index.
Exercise 5:
You have the list nums = [5, 10, 15, 20, 25]. Remove the last two elements using
the del statement and slice notation.
Exercise 6:
Exercise 7:
Start with the list cities = ["New York", "Paris", "London", "Tokyo",
"Berlin"]. Use the del statement to remove the first three elements using slicing.
Exercise 8:
Exercise 9:
Create a list numbers = [100, 200, 300, 400, 500]. Use the del statement to
remove the element at index 3.
Exercise 10:
7
Given a list names = ["Alice", "Bob", "Charlie", "David"], remove the element
at the second-to-last position using the pop() method with the appropriate index.
11 List Interview Questions
1. Reversing a List
● Given a list numbers = [1, 2, 3, 4, 5], reverse the list using slicing and
return the result.
TG
● Given two lists list1 = [1, 2, 3] and list2 = [4, 5, 6], concatenate the
two lists into a new list and return the result.
3. Extracting Sublist
● You have a list letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']. Extract
the sublist ['c', 'd', 'e'] using slicing.
4. Remove Duplicates
5. Element Replacement
● You have a list colors = ['red', 'green', 'blue', 'yellow']. Replace
the element at index 1 with the value 'orange' and return the updated list.
● Given a list numbers = [10, 20, 30, 40, 50, 60], split the list into two
sublists: one containing the first half and the other containing the second half.
Given a list chars = ['a', 'b', 'c'], repeat the elements of the list 3 times
7
●
and return the new list.
9. Insert Sublist
11
● Given two lists main_list = [10, 20, 30, 40] and sub_list = [50, 60],
insert sub_list between 20 and 30 in main_list using slicing, and return the
result.
● You have a list numbers = [100, 200, 300, 400, 500, 600]. Reverse only
TG
7
print the result.
5. Convert Tuple to List
Given a tuple values = (5, 10, 15), convert it to a list, add the value 20, and
convert it back to a tuple.
11
Intermediate Tuple Operations
6. Tuple Slicing
Given words = ("hello", "world", "Python", "is", "fun"), slice the
tuple to print only the middle three elements.
TG
7
Tuple Manipulation and Indexing
11
16. Extract Every Second Element
Given elements = (10, 20, 30, 40, 50, 60), create a new tuple that
includes every second element from the original tuple.
17. Find the Sum of Tuple Elements
Given values = (10, 15, 20, 25), calculate and print the sum of all elements
in the tuple.
18. Swap Values Using Tuples
Given a = 5 and b = 10, use tuple unpacking to swap their values and print the
TG
result.
19. Merge and Deduplicate Tuples
Given tuple_a = (1, 2, 3, 4) and tuple_b = (3, 4, 5, 6), merge the
two tuples, remove duplicates, and print the result as a tuple.
20. Create a Tuple from a Range of Numbers
Create a tuple that contains all even numbers between 2 and 20, inclusive, and print
the result.
Set Operations
7
the two sets.
5. Intersection of Two Sets
Given set_x = {"apple", "banana", "cherry"} and set_y =
{"cherry", "date", "banana"}, find and print the intersection.
11
Intermediate Set Operations
7
Challenging Set Operations
11
16. Check Subset
Given small_set = {1, 2} and large_set = {1, 2, 3, 4}, check if
small_set is a subset of large_set and print the result.
17. Check Superset
Given superset = {1, 2, 3, 4, 5} and subset = {2, 3}, check if
superset is a superset of subset and print the result.
18. Freeze a Set
TG
7
'notifications': True}, remove the 'volume' key using pop() and print the
dictionary.
5. Check if Key Exists in Dictionary
Given employee = {'id': 101, 'name': 'Emma', 'department':
11 'HR'}, check if 'department' exists in the dictionary using get() and print the
result.
7
Given two lists keys = ['name', 'age'] and values = ['Alice', 30],
create a dictionary by zipping them and print the result.
11
Nested Dictionary and Set Operations
7
Miscellaneous Dictionary Tasks
11
26. Create Dictionary of Squares
Given a list numbers = [1, 2, 3, 4], create a dictionary where each key is a
number and the value is its square. Print the result.
27. Filter and Print Dictionary Keys as String
Given sample = {'a': 1, 'b': 2, 'c': 3, 'd': 4}, retrieve only the keys
as a single comma-separated string (e.g., 'a, b, c, d').
28. Create a Nested Dictionary from Two Lists
TG
7
"B" if it’s between 80 and 89, "C" if it’s between 70 and 79, "D" if it’s between 60
and 69, and "F" otherwise.
5. Check for Vowel or Consonant
Ask the user for a single letter input. Use if-elif-else to print "Vowel" if it’s a
11 vowel (a, e, i, o, u) and "Consonant" otherwise.
Take a year as input from the user. Use if-else to print "Leap Year" if it’s a leap
year, otherwise print "Not a Leap Year".
7. Even or Odd
Take an integer input from the user and use if-else to check if it’s even or odd,
then print the result.
8. Password Validator
Ask the user for a password input. Print "Access Granted" if the password
matches "OpenSesame", otherwise print "Access Denied".
9. Max of Three Numbers
Take three numbers as input. Use if-elif-else to print the largest of the three
numbers.
10. BMI Calculator
Ask the user to enter their weight (in kg) and height (in meters). Calculate the BMI
and use if-elif-else to classify it as "Underweight" (BMI < 18.5), "Normal
weight" (18.5 <= BMI < 24.9), "Overweight" (25 <= BMI < 29.9), or "Obese"
(BMI >= 30).
Advanced if-elif-else Exercises
7
Take the purchase amount as input. Print the discount based on the amount: 5% for
up to $100, 10% for $101-$500, and 15% for more than $500.
15. Triangle Type by Sides
Take three side lengths as input. Use if-elif-else to print "Equilateral" if all
11 sides are equal, "Isosceles" if two sides are equal, and "Scalene" if all sides
are different.
7
6. Print Numbers from 10 to 1
Use a loop to print numbers from 10 down to 1.
7. Print a Series of Asterisks
Use a loop to print a series of 7 asterisks (*) in a row.
11
8. Count Down from 5 to 1
Write a loop to count down from 5 to 1, printing each number.
9. Print a List of Fruits
Given a list of fruits ["apple", "banana", "cherry"], use a loop to print each
fruit.
10. Print Square of Numbers from 1 to 5
Use a loop to print the square of each number from 1 to 5 (1, 4, 9, 16, 25).
TG