Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
37 views

Python Exercises

Python

Uploaded by

559aryan.ar3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Python Exercises

Python

Uploaded by

559aryan.ar3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python Exercises

Basic String Exercises

1. Concatenate and Print Strings


Given two strings first_name = "John" and last_name = "Doe",
concatenate them with a space in between and print the full name.
2. Print String with Escape Characters
Print the following string exactly as shown:
"Hello, "she said, "welcome to the party!"
3. Extract and Print a Substring
Given sentence = "Python is amazing!", extract the substring "Python"
and print it.

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

9. Replace Characters in a String


Given text = "I love apples", replace "apples" with "oranges" and print
the new string.
10. Check if String Contains a Substring
Given phrase = "The quick brown fox", print True if "fox" is in the phrase,
otherwise print False.

Intermediate String Exercises

11. Reverse a String


Given message = "Python", reverse the string and print the result ("nohtyP").
12. Slice and Print Last Three Characters
Given word = "Fantastic", slice and print the last three characters of the string.
13. Print Every Second Character
Given data = "abcdefghij", print every second character from the string.
14. Count and Print Vowels in a String
Given sentence = "I love programming", count the vowels (a, e, i, o,
u) and print the total number of vowels.
15. Format and Print Decimal Numbers
Given value = 5.6789, use string formatting to print the number rounded to two
decimal places (5.68).
16. Strip Whitespace and Print
Given text = " Hello, World! ", remove the leading and trailing whitespace
and print the result.
17. Interleave Two Strings
Given two strings str1 = "abc" and str2 = "123", interleave them to produce
"a1b2c3" and print the result.
18. Print Words Separately in Reverse Order
Given quote = "Live Laugh Love", split the string into words, reverse the order
of the words, and print them as "Love Laugh Live".
19. Print Initials from Full Name
Given a full name full_name = "Albert Einstein", extract the initials
("A.E.") and print them.

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

1. Print Variables with Formatting


Ask the user for their name and age. Print a message using f-strings in the format:
TG

"Hello, [name]! You are [age] years old."


2. Concatenate Multiple User Inputs
Take three inputs from the user for first name, middle name, and last name.
Concatenate them with spaces and print the full name.
3. Convert String Input to Integer
Ask the user to input their birth year. Calculate and print their age by subtracting the
birth year from the current year (use a variable for the current year).
4. Convert and Print Temperature
Ask the user for a temperature in Celsius. Convert it to Fahrenheit (using the formula
F = C * 9/5 + 32) and print the result.
5. String Length from User Input
Take a string input from the user and print the length of the input.
6. Swap Two Variables with Temp Variable
Ask the user to input two numbers and store them in variables a and b. Swap the
values using a temporary variable and print the swapped values.
7. Swap Two Variables without Temp Variable
Take two number inputs from the user, assign them to x and y, then swap their
values without using a temporary variable and print the result.
8. Calculate Simple Interest
Take inputs for principal, rate of interest, and time (in years) from the user. Calculate
simple interest using the formula SI = (P * R * T) / 100 and print the result.
9. Area of a Circle
Take the radius of a circle as input and calculate the area using the formula Area =
π * r^2 (use π = 3.14159 as a variable).
10. BMI Calculator
Ask the user to input their weight (in kg) and height (in meters). Calculate their BMI
using the formula BMI = weight / height^2 and print the result.

Intermediate Exercises

11. Round Float to Two Decimals


Take a floating-point number as input and print it rounded to two decimal places.
12. Convert Hours and Minutes to Total Minutes

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

between them using the formula distance = √((x2 - x1)^2 + (y2 -


y1)^2) and print the result.
16. Percentage Calculator
Ask the user to enter marks for three subjects. Calculate the percentage (assume
total marks for each subject is 100) and print the result.
17. Convert Minutes to Hours and Minutes
Take an integer input for a total number of minutes, then convert it to hours and
minutes format and print (e.g., 130 minutes = 2 hours, 10 minutes).
18. Calculate Volume of Cylinder
Take inputs for radius and height of a cylinder, then calculate the volume using
volume = π * r^2 * h (use π = 3.14159) and print the result.
19. Seconds in Days, Hours, and Minutes
Ask the user to input a number of seconds. Convert it to days, hours, and minutes
and print in the format X days, Y hours, Z minutes.
20. Convert Days to Years, Weeks, and Days
Take an integer input for a number of days, then convert it to years, weeks, and
remaining days and print (assume 1 year = 365 days, 1 week = 7 days).
Escape Sequences

1. Print Quotation Marks in a String

Print the following sentence using escape sequences:

`"Python is fun!" he said.`

2. Newline Escape Sequence

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:

`Name`, `Age`, `Location`


TG

`Alice`, `30`, `New York`

4. Backslash in a String

Print the file path `C:\Users\Documents\Report.docx` by using escape sequences to


include backslashes.

5. Carriage Return Escape Sequence

Use the carriage return escape sequence `\r` to print the following output:

`Starting... Overwritten`

Op : Overwritten

6. Double Quotes Inside Single Quotes


Print the following text exactly as shown, using escape sequences:

'He said, "It's a beautiful day!"'

7. Backspace Escape Sequence

Use the backspace escape sequence `\b` to print the word `Hell` by typing `Hello` in
the code and removing the last character.

8. Form Feed Escape Sequence

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.

10. Using Multiple Escape Sequences


TG

Combine `\t` and `\n` to format the following text:

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:

Given a list fruits = ["apple", "banana", "cherry", "date"], use slicing to

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:

Create a list months = ["January", "February", "March", "April"]. Insert


"May", "June", and "July" between "March" and "April" using slicing and extend().

List Remove, Del, Pop

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:

Given a list animals = ["dog", "cat", "rabbit", "hamster"], remove the


element at index 2 using the pop() method and store the removed element in a variable.

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:

You have the list months = ["January", "February", "March", "April",


"May", "June"]. Use the remove() method to delete "April" from the list.

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

2. Merging Two Lists

● 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

● Given a list numbers = [1, 2, 3, 1, 4, 2, 5], remove duplicate elements


without using loops or conditions, and return the result. (Hint: Use a combination of
set and list).

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.

6. Splitting a List in Two

● 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.

7. Shallow Copy of List

● Create a shallow copy of the list fruits = ["apple", "banana", "cherry"]


and return both the original and copied list.

8. Repeating Elements in List

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.

10. Reversing Part of a List

● You have a list numbers = [100, 200, 300, 400, 500, 600]. Reverse only
TG

the elements from index 2 to 4 and return the updated list.


Tuple Operations

Basic Tuple Operations

1. Access Tuple Element


Given a tuple numbers = (10, 20, 30, 40, 50), access and print the third
element.
2. Concatenate Tuples
Given two tuples t1 = (1, 2, 3) and t2 = (4, 5, 6), concatenate them into
a single tuple and print the result.
3. Check Element in Tuple
Given fruits = ("apple", "banana", "cherry"), check if "banana" is in
the tuple and print the result.
4. Convert List to Tuple
Given a list colors = ["red", "green", "blue"], convert it to a tuple and

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. Unpack Tuple Elements


Given a tuple coords = (10, 20), unpack it into variables x and y, then print both
values.
8. Find Length of Tuple
Given a tuple letters = ("a", "b", "c", "d", "e"), find and print its
length using a built-in function.
9. Get Minimum and Maximum Values
Given temperatures = (70, 65, 80, 75, 68), find and print both the
minimum and maximum values.
10. Multiply Tuple Elements
Given a tuple nums = (1, 2, 3), multiply all elements by 3 and print the resulting
tuple.

Advanced Tuple Operations


11. Count Occurrences of Element in Tuple
Given data = (5, 3, 5, 2, 5, 7, 5), count how many times 5 appears in the
tuple and print the result.
12. Find Index of an Element
Given names = ("Alice", "Bob", "Charlie", "David"), find and print the
index of "Charlie".
13. Reorder a Tuple in Descending Order
Given scores = (55, 70, 65, 85, 75), convert the tuple to a list, sort it in
descending order, and convert it back to a tuple.
14. Join Tuples Using Addition
Given tuple1 = ("A", "B") and tuple2 = ("C", "D"), create a new tuple
joined_tuple that joins both and print the result.
15. Create a Tuple with Repeated Elements
Create a tuple with the word "repeat" repeated five times and print the result.

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

Basic Set Operations

1. Add Element to Set


Given a set fruits = {"apple", "banana", "cherry"}, add the element
"orange" to the set and print the result.
2. Remove Element from Set
Given numbers = {1, 2, 3, 4, 5}, remove the element 3 from the set and
print the result.
3. Check if Element is in Set
Given animals = {"cat", "dog", "fish"}, check if "dog" is in the set and
print the result.
4. Union of Two Sets
Given set_a = {1, 2, 3} and set_b = {3, 4, 5}, find and print the union of

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

6. Difference of Two Sets


Given set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6}, find and print the
difference of set1 from set2.
TG

7. Symmetric Difference of Sets


Given A = {"red", "blue", "green"} and B = {"green", "yellow",
"blue"}, find and print the symmetric difference of the two sets.
8. Copy a Set
Given colors = {"red", "green", "blue"}, create a copy of the set and
print the copied set.
9. Convert List to Set and Remove Duplicates
Given a list duplicates = [1, 2, 2, 3, 4, 4, 5], convert it to a set to
remove duplicates, then print the set.
10. Convert Set to List
Given unique_numbers = {5, 10, 15, 20}, convert the set to a list and print
the result.

Advanced Set Operations


11. Find Maximum Element in Set
Given data = {12, 34, 5, 76, 9}, find and print the maximum element in the
set.
12. Find Minimum Element in Set
Given values = {100, 45, 78, 32, 15}, find and print the minimum element
in the set.
13. Clear All Elements in Set
Given tasks = {"task1", "task2", "task3"}, clear all elements from the
set and print the result.
14. Set Length
Given languages = {"Python", "Java", "C++", "JavaScript"}, find and
print the number of elements in the set.
15. Add Multiple Elements to Set
Given letters = {"a", "b"}, add the elements "c", "d", and "e" at once
using update() and print the result.

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

Given a set mutable_set = {"a", "b", "c"}, convert it into an immutable


frozenset and print the result.
19. Unique Characters from String
Given a string text = "hello world", convert it into a set to display only unique
characters, then print the set.
20. Find Common Elements Between Three Sets
Given set1 = {1, 2, 3, 4}, set2 = {2, 3, 5, 6}, and set3 = {3, 6,
7}, find and print the elements that are common across all three sets.
Dictionary Exercises

Basic Dictionary Operations

1. Access Dictionary Value by Key


Given person = {'name': 'Alice', 'age': 25, 'city': 'New York'},
access and print the value of the key 'age'.
2. Add New Key-Value Pair
Start with product = {'name': 'Laptop', 'brand': 'Dell'}. Add a new
key-value pair 'price': 1200 and print the updated dictionary.
3. Update Existing Key’s Value
Given student = {'name': 'John', 'grade': 'A'}, update the 'grade' to
'A+' and print the dictionary.
4. Remove Key-Value Pair
Given settings = {'theme': 'dark', 'volume': 50,

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.

Intermediate Dictionary Operations


TG

6. Merge Two Dictionaries


Given dict1 = {'a': 1, 'b': 2} and dict2 = {'c': 3, 'd': 4}, merge
dict2 into dict1 and print the result.
7. Get All Keys from a Dictionary
Given info = {'name': 'David', 'age': 34, 'city': 'Chicago'},
retrieve and print all keys using keys().
8. Get All Values from a Dictionary
Given data = {'x': 10, 'y': 20, 'z': 30}, retrieve and print all values
using values().
9. Convert Keys to List
Given sample = {'name': 'Anna', 'age': 25, 'city': 'Boston'},
convert the dictionary keys to a list and print it.
10. Convert Values to List
Given player = {'name': 'Ronaldo', 'team': 'Manchester',
'position': 'Forward'}, convert the dictionary values to a list and print it.

Advanced Dictionary Manipulations


11. Use setdefault() to Add Default Key-Value
Given config = {'resolution': '1080p'}, use setdefault() to add a
default key 'language': 'English' if it doesn’t exist, and print the dictionary.
12. Extract Specific Keys into a New Dictionary
Given person = {'name': 'Bob', 'age': 30, 'city': 'San
Francisco', 'job': 'Engineer'}, create a new dictionary containing only
'name' and 'job' keys.
13. Clear All Elements in Dictionary
Given items = {'item1': 100, 'item2': 200, 'item3': 300}, clear all
elements from the dictionary and print it.
14. Get Dictionary Length
Given profile = {'username': 'alex123', 'email':
'alex@example.com', 'role': 'admin'}, find and print the number of items
in the dictionary.
15. Create Dictionary from Two Lists

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

16. Create Dictionary Using fromkeys()


Create a dictionary with keys ['a', 'b', 'c'] where all values are set to 0 using
fromkeys() and print it.
17. Access Nested Dictionary Value
TG

Given family = {'parents': {'mother': 'Alice', 'father':


'Bob'}}, access the value of 'mother' and print it.
18. Copy a Dictionary
Given original = {'x': 5, 'y': 10}, create a copy of the dictionary and print
both the original and copied dictionary.
19. Remove and Return Last Item
Given settings = {'theme': 'dark', 'font': 'Arial', 'size': 12},
use popitem() to remove and print the last item from the dictionary.
20. Update Multiple Key-Values at Once
Given config = {'resolution': '720p', 'fullscreen': False}, update
both keys at once to 'resolution': '1080p' and 'fullscreen': True, then
print the updated dictionary.

Dictionary Conversion and Retrieval


21. Find Minimum Value in Dictionary
Given marks = {'math': 78, 'science': 84, 'history': 75}, find and
print the minimum value.
22. Find Maximum Key Alphabetically
Given chars = {'d': 1, 'b': 2, 'a': 3, 'c': 4}, find and print the key
that comes last alphabetically.
23. Convert Dictionary to List of Tuples
Given person = {'name': 'Tom', 'age': 28}, convert the dictionary to a list
of tuples and print it.
24. Combine Values of Two Dictionaries with Same Keys
Given dict1 = {'a': 100, 'b': 200} and dict2 = {'a': 300, 'b':
100}, create a new dictionary with the same keys but values summed, and print it.
25. Reverse Keys and Values in Dictionary
Given original = {'name': 'Alice', 'job': 'Developer'}, create a
new dictionary with keys and values swapped.

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

Given keys = ['outer', 'inner'] and values = ['outside',


'inside'], create a dictionary with 'outer' as a key whose value is another
dictionary {'inner': 'inside'} and print it.
29. Combine Dictionaries by Overwriting Keys
Given dict_a = {'x': 1, 'y': 2} and dict_b = {'y': 3, 'z': 4},
combine them such that dict_b overwrites any existing keys in dict_a.
30. Retrieve and Delete Specific Key
Given data = {'id': 123, 'name': 'Alice', 'age': 25}, use pop() to
retrieve and delete the value of the key 'name', then print the value and the
modified dictionary.
If-Else-elif

Basic if-else Exercises

1. Compare Two Numbers


Ask the user to input two numbers. Use if-else to print which number is larger, or if
they are equal.
2. Check if Number is Positive or Negative
Take an integer input from the user. Print "Positive" if the number is positive,
"Negative" if it's negative, and "Zero" if it’s zero.
3. Simple Calculator
Take two numbers and an operator (+, -, *, /) as input from the user. Use
if-elif-else to perform the specified operation and print the result.
4. Grade Classification
Ask the user for a score between 0 and 100. Print "A" if the score is 90 or above,

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.

Intermediate if-elif-else Exercises

6. Check for Leap Year


TG

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

11. Temperature Classification


Ask the user for the current temperature. Use if-elif-else to print "Cold"
(temperature < 10), "Cool" (10 <= temperature < 20), "Warm" (20 <= temperature <
30), and "Hot" (temperature >= 30).
12. Determine the Day Type
Ask the user for a day of the week (1 for Monday to 7 for Sunday). Use
if-elif-else to print "Weekday" for Monday to Friday and "Weekend" for
Saturday and Sunday.
13. Electricity Bill Calculation
Ask the user for electricity usage in kWh. Use if-elif-else to calculate the bill:
0.10/kWh for usage up to 100 kWh, 0.15/kWh for 101-200 kWh, 0.20/kWh for
201-300 kWh, and 0.25/kWh for more than 300 kWh.
14. Discount Based on Purchase Amount

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.

Complex if-elif-else Exercises


TG
16. Movie Ticket Price
Ask the user for their age. Use if-elif-else to print the ticket price: $10 for age <
12, $15 for age 12-17, $20 for age 18-59, and $12 for age 60 and above.
17. Basic Tax Calculator
Take the income as input. Use if-elif-else to calculate the tax rate: 5% for
income up to $10,000, 10% for $10,001-$50,000, 15% for $50,001-$100,000, and
20% for more than $100,000.
18. Number Classification
Take a number as input. Use if-elif-else to print "Single-digit" if it has 1
digit, "Double-digit" if it has 2 digits, and "Multi-digit" if it has more than 2
digits.
19. Grade Boundary Checker
Ask the user to input a grade letter (A, B, C, D, or F). Use if-elif-else to print
the grade boundaries: 90-100 for A, 80-89 for B, 70-79 for C, 60-69 for D, and below
60 for F.
20. Calculate Shipping Cost Based on Weight
Take a package weight as input in kg. Use if-elif-else to determine the shipping
cost: $5 for weight up to 1 kg, $10 for 1.1-5 kg, $20 for 5.1-10 kg, and $50 for more
than 10 kg.
Loops

Basic Loop Exercises

1. Print Numbers from 1 to 5


Write a loop to print numbers from 1 to 5.
2. Print "Hello" 5 Times
Use a loop to print the word "Hello" five times.
3. Print Odd Numbers from 1 to 9
Use a loop to print the odd numbers from 1 to 9 (1, 3, 5, 7, 9).
4. Sum of First 5 Natural Numbers
Use a loop to calculate and print the sum of the first 5 natural numbers (1 + 2 + 3 + 4
+ 5).
5. Print Each Letter in a Word
Ask the user for a word and use a loop to print each letter of the word on a new line.

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

You might also like