Menu

Python Exercises – Level 1

Join thousands of students who advanced their careers with MachineLearningPlus. Go from Beginner to Data Science (AI/ML/Gen AI) Expert through a structured pathway of 9 core specializations and build industry grade projects.

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.

Image

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:

find_numbers(100, 200)

Expected Output:

112,119,126,133,147,154,161,168,182,189,196

Hints:

Use the range(#start, #stop) function to iterate over the specified range.

Show Solution
def find_numbers(start, end):
    result = []
    for i in range(start, end + 1):
        if i % 7 == 0 and i % 5 != 0:
            result.append(str(i))
    return ','.join(result)

# Call the function with specific start and end values
print(find_numbers(100, 200))
112,119,126,133,147,154,161,168,182,189,196

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

Image

Input:

generate_square_dict(8)

Expected Output:

{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.
Show Solution

def generate_square_dict(n):
    d = dict()
    for i in range(1, n + 1):
        d[i] = i * i
    return d

generate_square_dict(8)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

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:

convert_input_to_list_and_tuple("3,6,5,3,2,8")

Expected Output:

(['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.
Show Solution

Here is the Solution:


def convert_input_to_list_and_tuple(input_string):
    values = input_string.split(",")
    return values, tuple(values)

convert_input_to_list_and_tuple("3,6,5,3,2,8")

(['3', '6', '5', '3', '2', '8'], ('3', '6', '5', '3', '2', '8'))

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:

str_obj = InputOutString()
str_obj.get_string()
str_obj.print_string()

Expected Output:

If the input string is "hello world", the output will be:

HELLO WORLD

Hints:

Utilize the __init__ method to initialize the class parameters.

Show Solution
class InputOutString:
    def __init__(self):
        self.s = ""

    def get_string(self):
        self.s = input("Enter a string: ")

    def print_string(self):
        print(self.s.upper())

# Test function

str_obj = InputOutString()
str_obj.get_string()
str_obj.print_string()

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:

calculate_q_values("100,150,180")  # 100,150,180 are possible values of D

Expected Output:

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.
Show Solution
import math

def calculate_q_values(d_values):
    C = 50
    H = 30
    value = []
    items = [float(x) for x in d_values.split(',')]
    for D in items:
        Q = round(math.sqrt((2 * C * D) / H))
        value.append(str(Q))
    return ','.join(value)

calculate_q_values('5,50,500')
'4,13,41'

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:

create_matrix(4, 3)

Expected Output:

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

Show Solution

def create_matrix(M, N):
    return [[i * j for j in range(N)] for i in range(M)]

create_matrix(4,3)

[[0, 0, 0], [0, 1, 2], [0, 2, 4], [0, 3, 6]]

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:

sort_words('banana,apple,grape,orange')

Expected Output:

'apple,banana,grape,orange'

Hints:

Use the split(',') method to break the input into a list of words and sorted() to sort the list.

Show Solution
def sort_words(words):
    return ','.join(sorted(words.split(',')))

sort_words('banana,apple,grape,orange')
'apple,banana,grape,orange'

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:

capitalize_lines(['Sundays are Fun', 'Monday is Done'])

Expected Output:

[['SUNDAYS ARE FUN', 'MONDAY IS DONE']]

Hints:

Use a list comprehension and the .upper() method to capitalize each line.

Show Solution

def capitalize_lines(lines):
    return [line.upper() for line in lines]

capitalize_lines(['Sundays are Fun', 'Monday is Done'])
['SUNDAYS ARE FUN', 'MONDAY IS DONE']

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:

unique_sorted_words('dog cat apple cat banana dog')

Expected Output:

'apple banana cat dog'

Hints:

Use a set to remove duplicates and sorted() to sort the words.

Show Solution

def unique_sorted_words(sentence):
    return ' '.join(sorted(set(sentence.split())))

unique_sorted_words('dog cat apple cat banana dog')    

'apple banana cat dog'

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:

binary_divisible_by_5('1101,1010,1111,1001')

Expected Output:

'1010'

Hints:

Convert each binary number to decimal using int() and check divisibility by 5.

Show Solution

def binary_divisible_by_5(binaries):
return ‘,’.join([b for b in binaries.split(‘,’) if int(b, 2) % 5 == 0])

binaries = ‘1101,1010,1111,1001’
binary_divisible_by_5(binaries)

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:

even_digit_numbers(1200, 2010)

Expected Output:

'2000,2002,2004,2006,2008'

Hints:

Check if all digits of a number are even using modulo operator %.

Show Solution
def even_digit_numbers(start, end):
    return ','.join([str(num) for num in range(start, end + 1) if all(int(digit) % 2 == 0 for digit in str(num))])

even_digit_numbers(1200, 2010)
'2000,2002,2004,2006,2008'

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:

count_letters_digits('Data123 Science 2024')

Expected Output:

{'LETTERS': 11, 'DIGITS': 7}

Hints:

Use isalpha() to check for letters and isdigit() to check for digits.

Show Solution

def count_letters_digits(sentence):
    counts = {"LETTERS": 0, "DIGITS": 0}
    for char in sentence:
        if char.isalpha():
            counts["LETTERS"] += 1
        elif char.isdigit():
            counts["DIGITS"] += 1
    return counts

count_letters_digits('Data123 Science 2024')

{'LETTERS': 11, 'DIGITS': 7}

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:

count_case('Hello World!')

Expected Output:

{'UPPER CASE': 2, 'LOWER CASE': 8}

Hints:

Use isupper() and islower() methods to distinguish between upper and lower case letters.

Show Solution

def count_case(sentence):
    counts = {"UPPER CASE": 0, "LOWER CASE": 0}
    for char in sentence:
        if char.isupper():
            counts["UPPER CASE"] += 1
        elif char.islower():
            counts["LOWER CASE"] += 1
    return counts
    
count_case('Hello World!')

{'UPPER CASE': 2, 'LOWER CASE': 8}

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:

sum_of_series(7)

Expected Output:

8638

Hints:

Use string multiplication and int() to construct each term of the series.

Show Solution
def sum_of_series(a):
    return sum(int(str(a) * i) for i in range(1, 5))


sum_of_series(7)

8638

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:

aCircle = Circle(3)
print(aCircle.area())

Expected Output:

28.26  # pi*r*r

Hints:

Use the formula πr² to calculate the area of the circle.

Show Solution
class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return self.radius ** 2 * 3.14

# Example usage
aCircle = Circle(3)
print(aCircle.area())

28.26

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:

aSquare = Square(4)
print(aSquare.area())

Expected Output:

16

Hints:

Override the area method in the Square class.

Show Solution
class Shape:
    def area(self):
        return 0

class Square(Shape):
    def __init__(self, length):
        self.length = length

    def area(self):
        return self.length ** 2

# Example usage
aSquare = Square(4)
print(aSquare.area())

16

Q17. Handle Division by Zero

Write a Python function that attempts to compute 10 / 0 and catches the exception.

Difficulty: Level 1

Input:

catch_zero_division()

Expected Output:

"division by zero!"

Hints:

Use try/except to handle the exception.

Show Solution

def catch_zero_division():
    try:
        return 10 / 0
    except ZeroDivisionError:
        print("division by zero!")

# Example usage
catch_zero_division()



division by zero!

Q19. Extract Username from Email

Create a Python program that extracts and prints the username from a given email address in the format [email protected]. Difficulty: Level 2 Input: ```python extract_username("[email protected]") </code></pre> <strong>Expected Output:</strong> <pre><code class="language-python">"alice" </code></pre> <strong>Hints:</strong> Use regular expressions to extract the username. 'Show
<pre><code> ```python import re def extract_username(email): match = re.match(r"(\w+)@(\w+\.\w+)", email) return match.group(1) # Example usage print(extract_username("[email protected]"))

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:

print(f(5))

Expected Output:

501

Hints:

Use a recursive function to compute the value of f(n).

Show Solution
def f(n):
    if n == 0:
        return 1
    else:
        return f(n - 1) + 100

# Example usage
print(f(5))
501

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:

print(generate_random_numbers())

Expected Output:

[160, 183, 194, 203, 224]

Hints:

Use random.sample() to generate random values from a specified range.

Show Solution

import random

def generate_random_numbers():
    return random.sample(range(150, 251), 5)

# Example usage
print(generate_random_numbers())


[189, 160, 192, 155, 168]

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:

print(generate_even_numbers())

Expected Output:

[160, 182, 200, 224, 246]

Hints:

Use random.sample() to pick random even numbers from a list.

Show Solution

import random

def generate_even_numbers():
    return random.sample([i for i in range(150, 251) if i % 2 == 0], 5)

# Example usage
print(generate_even_numbers())


[192, 168, 176, 170, 242]

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:

print(measure_execution_time())

Expected Output:

Execution Time: 0.00012 seconds

Hints:

Use time.time() to measure the time.

Show Solution
import time

def measure_execution_time():
    start = time.time()
    for _ in range(10000):
        1 + 1
    end = time.time()
    return f"Execution Time: {end - start} seconds"

# Example usage
print(measure_execution_time())

Execution Time: 0.0005338191986083984 seconds

Scroll to Top
Image
Course Preview

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free Sample Videos:

Image

Machine Learning A-Z™: Hands-On Python & R In Data Science

Image

Machine Learning A-Z™: Hands-On Python & R In Data Science

Image

Machine Learning A-Z™: Hands-On Python & R In Data Science

Image

Machine Learning A-Z™: Hands-On Python & R In Data Science

Image

Machine Learning A-Z™: Hands-On Python & R In Data Science

Scroll to Top