Basic Python Exercise for Beginners

Posted in /  

Basic Python Exercise for Beginners
vinaykhatri

Vinay Khatri
Last updated on December 14, 2024

    Learning the basic syntax of Python is not enough. It is effortless to learn the syntax of any programming language. Syntax and statements are just some plain English words. The only way to hone your Python skill is by practicing the exercise problems. If you have learned the basics of Python, such as keywords, operators, conditional statements, loops, functions, and classes. Now it’s time to test your logic and Python skills with basic Python exercises.

    In the Basic Python Exercise article, you will see some of the beginner’s Python problem statements and their solutions. Before checking out the solution, please try to attempt the problem statement by yourself.

    Note: A Problem statement can have multiple algorithms or solutions. The ones we have mentioned in this tutorial are efficient. You can have your own way of solving the problem.

    Prerequisites

    To tackle the problems discussed in this Python fundamental exercise, you have the basic knowledge of Python, which include:

    • Python Operators
    • Python Keywords
    • Python Data Types
    • Python Loops
    • Python Conditional Statements
    • Python Exception Handling
    • Python File Handaling

    Let’s get started

    Python Exercise 1: Write a Python program to make a simple arithmetic calculator.

    Problem Statement

    We need to write a Python program that accepts two numbers and an arithmetic operator from the user and performs the arithmetic operation on those two numbers.

    Refer Articles

    Solution

    #function to add two numbers
    def add(a,b):
        return a+b
    
    #function to add subtract numbers
    def subtract(a,b):
        return a-b
    
    #function to add multiply numbers
    def multiply(a,b):
        return a*b
    
    #function to divide two numbers
    def divide(a,b):
        return a/b
    
    if __name__ == '__main__':
        a, operator, b = input("Enter the two numbers along with operator eg(12 + 13 ): ").split()
    
        #Python structural pattern matching
        match operator:
            case "+":
                result = add(int(a),int(b))
            case "-":
                result = subtract(int(a), int(b))
            case "*":
                result = multiply(a,b)
            case "/":
                result =  divide(a,b)
    
    print(f"{a} {operator} {b} = {result}")

    Output

    Enter the two numbers along with operator eg(12 + 13 ): 14 * 3
    14 * 3 = 42

    Python Exercise 2: Write a Python program to print the sum of first n numbers.

    Problem Statement

    You need to write a Python program that accepts an N positive integer from the user and print the sum upto that N number For example, if the user input 4 the program should print 10 N = 4 1 + 2 + 3 + 4 = 10 .

    Refer Article

    Solution

    def sum_uptoN(n):
        total = 0
    
        #sum upto n
        for i in range(1, n+1):
            total += i
    
        return total
    
    n = int(input("Enter a positive number n: "))
    
    print(f"The sum of the first positive {n} numbers is: ", sum_uptoN(n))

    Output

    Enter a positive number n: 10
    The sum of the first positive 10 numbers is:  55

    Python Exercise 3: Write a Python program to print all the prime numbers between two intervals

    Problem Statement You need to write a Python script that asks the user to enter an interval of positive numbers and print all the prime numbers of that interval.

    Topics to consider

    Solution

    #function that checks if a number is a prime or not
    def check_prime(num):
        for i in range(2, (num//2)+1):
            #if the number is not a prime
            if num %i ==0:
                return False
    
        #return True if the number is a prime
        return True
    
    #print the prime number between the given intervals
    def print_prime(a, b):
        for i in range(a, b+1):
            #check if the number is a prime
            if check_prime(i):
                print(i, end = " ")
    
    a , b = map(int, input("Enter the interval range eg(10 50): ").split())
    
    print(f"The prime numbers between {a} and {b} are: ")
    print_prime(a, b)

    Output

    The prime numbers between 10 and 50 are: 
    11 13 17 19 23 29 31 37 41 43 47

    Python Exercise 4: FizzBuzz Problem

    Problem Statement

    Given a positive integer number n. You need to write a Python script that iterates through 1 to n. Prints Fizz if the number is divisible by 3, print Buzz if the number is divisible by 5, Print “FizzBuzz” if the number is divisible by both 3 and 5, else it simply print the number.

    Example

    n = 10 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz

    Solution

    #function to print fizzBuzz sequence
    def fizzBuzz(n):
        for i in range(1, n+1):
            #if number is divisible by 3 and 5
            if i%3==0 and i%5==0:
                print("FizzBuzz", end =" ")
    
            #if number is divisible by 3
            elif i%3==0:
                print("Fizz", end =" ")
    
            #if number is divisible by 5
            elif i%5==0:
                print("Buzz", end =" ")
    
            #if number is not divisible by 3, or 5
            else:
                print(i, end= " ")
    
    n = int(input("Enter the value of n: "))
    
    fizzBuzz(n)

    Output

    Enter the value of n: 20
    1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz

    Python Exercise 5: Remove first n Characters from a string

    Problem Statement

    You have given a non-empty string, and a positive integer number n (less than the length of the string). You need to write a Python function that returns by removing the first n characters from the string.

    Example

    string = "Hi There! Welcome to TechGeekBuzz" n = 10 Remove the first 10 characters from the string. Output: Welcome to TechGeekBuzz

    Refer Topics

    Solution

    # function to remove first n characters
    def remove_char(string, n):
        # return the string starts from n index value
        return string[n:]
    
    #string value
    string = "Hi There! Welcome to TechGeekBuzz"
    
    #number of characters to remove
    n = 10
    
    print(remove_char(string, n))

    Output

    Welcome to TechGeekBuzz

    Python Exercise 6: Write a Python program that accepts a list of 10 float numbers from the user.

    Problem Statement

    You need to write a Python program that accepts 10 float numbers from the user and adds them to a list.

    Example: If user enters 10 20 30 40 50 60 70 80 90 100

    Output: [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.00]

    Refer Topics:

    Solution

    sequence = input(
        "Enter the 10 float numbers separated by space\n (eg 12 13 14 15 16): ")
    
    float_list = list(map(float, sequence.split()))
    
    print("Your List of Float numbers is: ", float_list)

    Output

    Enter the 10 float numbers separated by space
     (eg 12 13 14 15 16): 10 20 30 40 50 60 70 80 90 100
    Your List of Float numbers is:  [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]

    Python Exercise 7: Python program to write data of one file to another except for lines 3, 6, and 9.

    Problem statement

    You have given a file data.txt, you need to write a Python program that reads the content from data.txt and writes its all content to new_data.txt except the lines 3, 6, and 9.

    Refer Topics

    Example

    data.txt new_data.txt
    Line 1 data Line 2 data Line 3 data Line 4 data Line 5 data Line 6 data Line 7 data Line 8 data Line 9 data Line 10 data Line 1 data Line 2 data Line 4 data Line 5 data Line 7 data Line 8 data Line 10 data

    Solution

    # read data from one file
    with open("data.txt", "r") as file:
        content = file.readlines()
    
    # write data into new file
    # except for lines 3, 6 and 9
    with open("new_data.txt", "w") as file:
        for line in range(len(content)):
            # if line is not 3, 6 or 9
            # write data into the new file
            if not (line+1 == 3 or line+1 == 6 or line+1 == 9):
                file.write(content[line])

    Python Exercise 8: Python program to print n number of the Fibonacci sequence using recursion.

    Problem Statement

    A Fibonacci sequence is a series of integers that start from 0 and 1, and every next number is decided by the sum of the previous two numbers. You need to write a Python code that asks the user to enter the value n, representing the length of the sequence. And a recursive function to print a Fibonacci sequence of n length.

    Example

    n = 10 Output: 0 0 1 2 3 5 8 13 21 34

    Refer topics:

    Solution

    # python recusive function to print nth fibonacci number
    def fibo_recur(n):
        # set the base condition
        if n <= 1:
            return n
        else:
            return fibo_recur(n-1) + fibo_recur(n-2)
    
    n = int(input("Enter the length of the sequence: "))
    
    for i in range(n):
        # print the nth fibonacci number
        print(fibo_recur(i), end=" ")

    Output

    Enter the length of the sequence: 10
    0 1 1 2 3 5 8 13 21 34

    Python Exercise 9: Python program to print the first non-repeated character from a string.

    Problem Statement: You have given a string and you need to find the first non-repeated characters.

    Example

    given_string = welcome to techgeekbuzz.com website Output l

    Refer Topics

    • Python String
    • Python for loop

    Solution

    # function that will return the non-repeated character
    
    def non_repeated_char(string):
    
        for char in string:
            # if the character is only occurred ones in the string
            if string.count(char) == 1:
                return char
        return None
    
    string = "welcome to techgeekbuzz.com website"
    print("The first non-repeating character is ", non_repeated_char(string))

    Output

    The first non-repeating character is:  l

    Python Exercise 10: Python program to count the occurrence of each item from a list.

    Problem Statement

    You have given a list with repeated items and you need to write a script that counts the occurrence of every list item.

    Example

    given_list = [10, 20, 30, 10, 30, 20, 20, 20, 40, 50] Output = {10 : 2, 20 : 4, 30: 2, 40: 1, 50: 1 }

    Refer Topics

    Solution

    #function to count occurance of items
    def count_occur(given_list):
        #initialize an empty list
        count = dict()
    
        #loop through the list
        for item in given_list:
            #if the item is not in the list
            if not item in count:
                #add the item to count
                #with 1 count number
                count[item] = 1
            else:
                count[item] +=1
        return count
    
    given_list = [10, 20, 30, 10, 30, 20, 20, 20, 40, 50]
    
    print(count_occur(given_list))

    Output

    {10: 2, 20: 4, 30: 2, 40: 1, 50: 1}

    Conclusion

    That’s it with our Python’s Basic Exercise Problems. In this article, you learned 10 Python problems and their solutions. The problem we have discussed in this article are the common and beginner-level problems, if you have a basic understanding of Python, it will be a piece of cake to solve all the above problems in one go. If you like this article or want to share your own code to solve the above problems please fill the comment box.

    People are also reading:

    Leave a Comment on this Post

    0 Comments