machine learning +
101 Polars Exercises for Data Analysis (with Solutions)
Python Exercises – Level 1
Python exercises to practice as a beginner. These are devised as mini tasks that you might need to apply when programming with Python.
This notebook contains Python exercises to practice as a beginner. These are devised as byte sized mini tasks that you might need to apply when programming with Python. By doing these, you gain more experience and tuned to applying Python for more practical situations.
Who is this for?
You already know Python basics and want to get practice or prepare for coding interviews, this will a good set to practice. You understand the python syntax and data types (integers, strings, lists, dictionaries, etc.) and you are able to write simple Python programs such as functions and use the standard library
Experience Level:
You have started learning Python recently or has only worked on small, straightforward projects.
Note: If you are looking for exercises on Data Analysis, check out the 101 Pandas Exercises.
Q1. Find numbers Divisible by 7, not by 5
Create a Python program that identifies all numbers between 100 and 300 (inclusive) that are divisible by 7 but not multiples of 5. The identified numbers should be displayed in a single line, separated by commas.
Level: Beginner
Input:
python
find_numbers(100, 200)
Expected Output:
python
112,119,126,133,147,154,161,168,182,189,196
Hints:
Use the range(#start, #stop) function to iterate over the specified range.
Q2: Generate Square Dictionary
Create a Python function that takes an integer ( n ) as input and generates a dictionary containing pairs ( (i, i^2) ) for all integers ( i ) from 1 to ( n ) (inclusive). The function should then return this dictionary.
Level: Beginner
Input:
python
generate_square_dict(8)
Expected Output:
python
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
Hints:
- Use the
dict()function to create an empty dictionary. - Iterate through the range from 1 to ( n ) using a loop.
Q3. Sequence to List and Tuple
Create a Python function that takes a sequence of comma-separated numbers as input and generates both a list and a tuple containing those numbers.
Level: Beginner
Input:
python
convert_input_to_list_and_tuple("3,6,5,3,2,8")
Expected Output:
python
(['3', '6', '5', '3', '2', '8'], ('3', '6', '5', '3', '2', '8'))
Hints:
- The input will be provided as a string.
- Use the
split(",")method to convert the string into a list. - The
tuple()method can convert a list into a tuple.
Q4. String Manipulation Class
Define a class that contains at least two methods: get_string to retrieve a string from console input and print_string to display the string in uppercase. Additionally, include a simple test function to validate the class methods.
Difficulty: Level 1
Input:
python
str_obj = InputOutString()
str_obj.get_string()
str_obj.print_string()
Expected Output:
If the input string is "hello world", the output will be:
python
HELLO WORLD
Hints:
Utilize the __init__ method to initialize the class parameters.
Q5. Calculate Q Values from D
Create a Python function that computes the value of ( Q ) using the formula:
$$
Q = \sqrt{\frac{(2 \cdot C \cdot D)}{H}}
$$
where ( C ) is 50 and ( H ) is 30. The function should take only ( D ) as input, which consists of a comma-separated sequence of values. The output should be rounded to the nearest integer and printed in a single line, separated by commas.
Difficulty: Level 1
Input:
python
calculate_q_values("100,150,180") # 100,150,180 are possible values of D
Expected Output:
python
18,22,24
Hints:
- Use the
math.sqrt()function to compute the square root. - Convert input values to float for calculation, and round the result using the
round()function.
Q6: Table Matrix
Create a Python program that takes two digits, M and N, as inputs and generates a two-dimensional array. The value at the i-th row and j-th column of the array should be i*j.
Difficulty: Level 2
Input:
python
create_matrix(4, 3)
Expected Output:
python
[[0, 0, 0],
[0, 1, 2],
[0, 2, 4],
[0, 3, 6]]
# Ex: 6 belongs to row=3, column=2
Hints:
Use a nested list comprehension to construct the 2D matrix.
Q7. Sort Comma-Separated Words
Create a Python program that accepts a sequence of comma-separated words as input and returns the words sorted in alphabetical order.
Difficulty: Level 2
Input:
python
sort_words('banana,apple,grape,orange')
Expected Output:
python
'apple,banana,grape,orange'
Hints:
Use the split(',') method to break the input into a list of words and sorted() to sort the list.
Q8. Capitalize All Lines
Create a Python program that takes a sequence of lines as input and returns each line capitalized.
Difficulty: Level 2
Input:
python
capitalize_lines(['Sundays are Fun', 'Monday is Done'])
Expected Output:
python
[['SUNDAYS ARE FUN', 'MONDAY IS DONE']]
Hints:
Use a list comprehension and the .upper() method to capitalize each line.
Q9. Unique Sorted Words
Create a Python program that accepts a sequence of whitespace-separated words as input and returns them sorted alphabetically with duplicates removed.
Difficulty: Level 2
Input:
python
unique_sorted_words('dog cat apple cat banana dog')
Expected Output:
python
'apple banana cat dog'
Hints:
Use a set to remove duplicates and sorted() to sort the words.
Q10. Binary Divisible by 5
Create a Python program that accepts a sequence of comma-separated 4-digit binary numbers as input and checks if they are divisible by 5. The valid numbers should be returned in a comma-separated sequence.
Difficulty: Level 2
Input:
python
binary_divisible_by_5('1101,1010,1111,1001')
Expected Output:
python
'1010'
Hints:
Convert each binary number to decimal using int() and check divisibility by 5.
Q11. All Even Digits
Create a Python program that finds all numbers between 1200 and 2100 (both inclusive) where each digit is an even number. The numbers should be returned as a comma-separated sequence.
Difficulty: Level 2
Input:
python
even_digit_numbers(1200, 2010)
Expected Output:
python
'2000,2002,2004,2006,2008'
Hints:
Check if all digits of a number are even using modulo operator %.
Q12. Count Letters and Digits
Create a Python program that accepts a sentence and calculates the number of letters and digits.
Difficulty: Level 2
Input:
python
count_letters_digits('Data123 Science 2024')
Expected Output:
python
{'LETTERS': 11, 'DIGITS': 7}
Hints:
Use isalpha() to check for letters and isdigit() to check for digits.
Q13. Count Upper and Lower Case
Create a Python program that accepts a sentence and calculates the number of uppercase and lowercase letters.
Difficulty: Level 2
Input:
python
count_case('Hello World!')
Expected Output:
python
{'UPPER CASE': 2, 'LOWER CASE': 8}
Hints:
Use isupper() and islower() methods to distinguish between upper and lower case letters.
Q14. Sum of a + aa + aaa + aaaa
Create a Python program that calculates the value of a + aa + aaa + aaaa for a given digit a.
Difficulty: Level 2
Input:
python
sum_of_series(7)
Expected Output:
python
8638
Hints:
Use string multiplication and int() to construct each term of the series.
Q15. Circle Class
Create a Python class Circle that accepts a radius as a parameter and has a method to compute the area of the circle.
Difficulty: Level 1
Input:
python
aCircle = Circle(3)
print(aCircle.area())
Expected Output:
python
28.26 # pi*r*r
Hints:
Use the formula πr² to calculate the area of the circle.
Q16. Shape and Square Area
Create a Python class Shape and a subclass Square. The Square class takes a length as a parameter and both classes have a method to compute the area. The area of Shape is 0 by default, while the area of Square is the square of its side length.
Difficulty: Level 2
Input:
python
aSquare = Square(4)
print(aSquare.area())
Expected Output:
python
16
Hints:
Override the area method in the Square class.
Q17. Handle Division by Zero
Write a Python function that attempts to compute 10 / 0 and catches the exception.
Difficulty: Level 1
Input:
python
catch_zero_division()
Expected Output:
python
"division by zero!"
Hints:
Use try/except to handle the exception.
Q18. Recursive Function for f(n)
Create a Python function f(n) such that f(n) = f(n-1) + 100 when n > 0 and f(0) = 1.
Difficulty: Level 2
Input:
python
print(f(5))
Expected Output:
python
501
Hints:
Use a recursive function to compute the value of f(n).
Q19. Generate Random Numbers
Write a Python function that generates a list of 5 random numbers between 150 and 250 (inclusive).
Difficulty: Level 1
Input:
python
print(generate_random_numbers())
Expected Output:
python
[160, 183, 194, 203, 224]
Hints:
Use random.sample() to generate random values from a specified range.
Q20. Generate Even Numbers
Write a Python function that generates a list of 5 even numbers randomly between 150 and 250 (inclusive).
Difficulty: Level 1
Input:
python
print(generate_even_numbers())
Expected Output:
python
[160, 182, 200, 224, 246]
Hints:
Use random.sample() to pick random even numbers from a list.
Q21. Measure Execution Time
Write a Python program to measure the execution time of the expression 2+2 repeated 10000 times.
Difficulty: Level 1
Input:
python
print(measure_execution_time())
Expected Output:
python
Execution Time: 0.00012 seconds
Hints:
Use time.time() to measure the time.
Free Course
Master Core Python — Your First Step into AI/ML
Build a strong Python foundation with hands-on exercises designed for aspiring Data Scientists and AI/ML Engineers.
Start Free Course →Trusted by 50,000+ learners
Related Course
Master Python — Hands-On
Join 5,000+ students at edu.machinelearningplus.com
Explore Course


