Python exercises for Beginners with solutions

These are the basic building blocks that you should master to have a great foundation in Python, as all other complex utils work using these structures. We aimed to take a broad approach to the solutions of the exercises here so that you could acquire a solid basis while using Python conditional and loop statements in this range of exercises.

Python If-Else Statements Explained

If-else statements in Python are used for decision-making. This is a very important idea to create programs that could answer different inputs and work for other cases.

Contents hide

Basic If-Else Example

age = 18

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Nested If-Else Example

score = 85

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
else:
    print("C")

Python If-Else and For Loop Solutions

Exercise 1: Temperature Classification

Write a Python program that classifies temperature based on user input.

Conditions:

  • If the temperature is above 30°C, print “Hot.”
  • If the temperature is between 20°C and 30°C, print “Warm.”
  • If the temperature is below 20°C, print “Cold.”

Solution:

temperature = float(input("Enter the temperature: "))

if temperature > 30:
    print("Hot")
elif 20 <= temperature <= 30:
    print("Warm")
else:
    print("Cold")

For Loops in Python (A Defining Feature)

You probably know that for loop in Python iterates over all kinds of sequences e.g., lists, tuples, or strings. This loop is something we must master for dealing with arrays, generating repetitive outputs, etc..

Basic For Loop Example

numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

For Loop with Range Example

for i in range(5):
    print(i)

Exercise 2: Sum of Numbers

Write a Python program to calculate the sum of numbers from 1 to n using a for loop.

Solution:

n = int(input("Enter a number: "))
total = 0

for i in range(1, n+1):
    total += i

print(f"The sum of numbers from 1 to {n} is {total}")

Exercise 3: Multiplication Table Generator

Write a Python program that prints the multiplication table of any number provided by the user.

Solution:

num = int(input("Enter a number: "))

for i in range(1, 11):
    print(f"{num} x {i} = {num*i}")

Combining If-Else and For Loop : Exercises for Mastery

To truly understand control flow, it is essential to combine both if-else and for loops. Let’s look at more advanced exercises that test your knowledge.Python If-Else and For Loop Solutions

Exercise 4: Even and Odd Numbers Classification

Write a Python program that takes a list of numbers and classifies them as even or odd.

Solution:

numbers = [10, 15, 22, 33, 42, 55, 60]

for number in numbers:
    if number % 2 == 0:
        print(f"{number} is even")
    else:
        print(f"{number} is odd")

Exercise 5: Find Prime Numbers >> If-Else and For Loop

Write a Python program that finds all prime numbers between 1 and 100.

Solution:

for num in range(2, 101):
    is_prime = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False 
            break
    if is_prime:
        print(num)

Exercise 6: Fibonacci Sequence Generator

Write a Python program that generates the first n Fibonacci numbers.

Solution:

n = int(input("Enter the number of Fibonacci terms: "))
a, b = 0, 1
count = 0

while count < n:
    print(a)
    a, b = b, a + b
    count += 1

Exercise 7: Grading System Based on Scores

Create a Python program that takes student scores and assigns grades based on the following criteria:

  • Score >= 90: Grade A
  • Score >= 80: Grade B
  • Score >= 70: Grade C
  • Score >= 60: Grade D
  • Score < 60: Grade F

Solution:

score = int(input("Enter your score: "))

if score >= 90:
    print("Grade A")
elif score >= 80:
    print("Grade B")
elif score >= 70:
    print("Grade C")
elif score >= 60:
    print("Grade D")
else:
    print("Grade F")

Visualizing Python Loop Execution

Diagram of Loop Control Flow

graph TD;
    Start --> Condition{"Condition Met?"};
    Condition -->|Yes| Process("Execute Code Block");
    Condition -->|No| End;
    Process --> Repeat("Return to Condition");
    Repeat --> Condition;
    End --> Stop;

This diagram represents the flow of control in a for loop. As long as the condition is met, the loop will continue executing the code block. Once the condition fails, the loop terminates.

Exercise 8: Factorial Calculation Using For Loop

The factorial of a number is the product of all positive integers less than or equal to that number. Write a Python program to calculate the factorial of a given number using a for loop.

Solution:

num = int(input("Enter a number: "))
factorial = 1

if num < 0:
    print("Factorial is not defined for negative numbers.")
elif num == 0:
    print("The factorial of 0 is 1.")
else:
    for i in range(1, num + 1):
        factorial *= i
    print(f"The factorial of {num} is {factorial}.")

Exercise 9: Reverse a String Using a For Loop

Write a Python program that takes a string as input and reverses it using a for loop.

Solution:

string = input("Enter a string: ")
reversed_string = ""

for char in string:
    reversed_string = char + reversed_string

print(f"The reversed string is: {reversed_string}")

Exercise 10: Find the Maximum Number in a List

Write a Python program to find the largest number in a list without using the max() function.

Solution:

numbers = [3, 41, 12, 9, 74, 15]
max_number = numbers[0]

for number in numbers:
    if number > max_number:
        max_number = number

print(f"The largest number in the list is: {max_number}")

Exercise 11: Count Vowels in a String

Create a Python program to count the number of vowels (a, e, i, o, u) in a given string using a for loop.

Solution:

string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:
    if char in vowels:
        count += 1

print(f"The number of vowels in the string is: {count}")

Exercise 12: Check for Palindrome

A palindrome is a word, number, phrase, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Write a Python program to check if a given string is a palindrome.

Solution:

string = input("Enter a string: ")
string = string.lower().replace(" ", "")  # Convert to lowercase and remove spaces

if string == string[::-1]:
    print("The string is a palindrome.")
else:
    print("The string is not a palindrome.")

Exercise 13: Generate a List of Squares

Write a Python program that takes an integer n as input and generates a list of squares of numbers from 1 to n.

Solution:

n = int(input("Enter a number: "))
squares = []

for i in range(1, n + 1):
    squares.append(i ** 2)

print(f"The list of squares from 1 to {n} is: {squares}")

Exercise 14: Sum of Digits of a Number

Write a Python program that takes a number as input and calculates the sum of its digits using a for loop.

Solution:

number = input("Enter a number: ")
sum_of_digits = 0

for digit in number:
    sum_of_digits += int(digit)

print(f"The sum of the digits is: {sum_of_digits}")

Exercise 15: FizzBuzz Problem

The FizzBuzz problem is a popular coding interview question. Write a Python program that prints the numbers from 1 to 100. However, for multiples of 3, print “Fizz” instead of the number, and for multiples of 5, print “Buzz.” For numbers that are multiples of both 3 and 5, print “FizzBuzz.”

Solution:

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Exercise 16: Find Common Elements in Two Lists

Write a Python program that takes two lists and finds the common elements between them.

Solution:

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
common_elements = []

for element in list1:
    if element in list2:
        common_elements.append(element)

print(f"The common elements are: {common_elements}")

Exercise 17: Find the Largest Even Number in a List

Write a Python program that finds the largest even number in a list. If there is no even number, it should display a message accordingly.

Solution:

numbers = [3, 7, 12, 43, 18, 29]
largest_even = None

for number in numbers:
    if number % 2 == 0:
        if largest_even is None or number > largest_even:
            largest_even = number

if largest_even:
    print(f"The largest even number is: {largest_even}")
else:
    print("There is no even number in the list.")

Exercise 18: Find Divisors of a Number

Write a Python program that takes a number as input and finds all its divisors using a for loop.

Solution:

num = int(input("Enter a number: "))
divisors = []

for i in range(1, num + 1):
    if num % i == 0:
        divisors.append(i)

print(f"The divisors of {num} are: {divisors}")

Exercise 19: Count Words in a Sentence

Write a Python program to count the number of words in a given sentence.

Solution:

sentence = input("Enter a sentence: ")
words = sentence.split()
word_count = len(words)

print(f"The number of words in the sentence is: {word_count}")

Exercise 20: Calculate the Sum of Odd Numbers

Write a Python program to calculate the sum of odd numbers from 1 to n, where n is provided by the user.

Solution:

n = int(input("Enter a number: "))
sum_odd = 0

for i in range(1, n + 1):
    if i % 2 != 0:
        sum_odd += i

print(f"The sum of odd numbers from 1 to {n} is: {sum_odd}")

Exercise 21: Find the Length of the Longest Word in a Sentence

Write a Python program to find the longest word in a sentence and its length.

Solution:

sentence = input("Enter a sentence: ")
words = sentence.split()
longest_word = max(words, key=len)

print(f"The longest word is '{longest_word}' with {len(longest_word)} characters.")

Exercise 22: Calculate Power Using a For Loop

Write a Python program that calculates the power of a number using a for loop. The program should take two inputs: the base and the exponent.

Solution:

base = int(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1

for _ in range(exponent):
    result *= base

print(f"{base} to the power of {exponent} is {result}")

Exercise 23: Find Numbers Divisible by Both 3 and 5

Write a Python program that finds all numbers between 1 and 100 that are divisible by both 3 and 5.

Solution:

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print(i)

Exercise 24: Count the Occurrence of a Character in a String

Write a Python program that takes a string and a character as inputs and counts how many times the character appears in the string.

Solution:

string = input("Enter a string: ")
char = input("Enter a character to count: ")
count = 0

for c in string:
    if c == char:
        count += 1

print(f"The character '{char}' appears {count} times in the string.")

Exercise 25: Find the Sum of the First n Natural Numbers Using a Formula

Write a Python program to find the sum of the first n natural numbers using the formula n(n + 1) / 2.

Solution:

n = int(input("Enter a number: "))
sum_n = n * (n + 1) // 2

print(f"The sum of the first {n} natural numbers is {sum_n}")

Exercise 26: Count the Number of Digits in a Number

Write a Python program to count how many digits a given number has.

Solution:

num = input("Enter a number: ")
print(f"The number {num} has {len(num)} digits.")

Exercise 27: Calculate the Product of a List of Numbers

Write a Python program that calculates the product of all the numbers in a given list.

Solution:

numbers = [2, 3, 4, 5]
product = 1

for number in numbers:
    product *= number

print(f"The product of the list is: {product}")

Exercise 28: Remove Duplicates from a List

Write a Python program that removes duplicate elements from a list.

Solution:

numbers = [1, 2, 3, 2, 4, 5, 1, 6]
unique_numbers = []

for number in numbers:
    if number not in unique_numbers:
        unique_numbers.append(number)

print(f"The list without duplicates: {unique_numbers}")

Exercise 29: Find the Second Largest Number in a List

Write a Python program to find the second largest number in a list.

Solution:

numbers = [12, 45, 78, 23, 89, 67]
largest = second_largest = float('-inf')

for number in numbers:
    if number > largest:
        second_largest = largest
        largest = number
    elif number > second_largest and number != largest:
        second_largest = number

print(f"The second largest number is: {second_largest}")

Exercise 30: Find Palindromic Numbers Between 1 and 1000

Write a Python program that prints all palindromic numbers between 1 and 1000. A palindromic number is a number that reads the same forward and backward.

Solution:

for num in range(1, 1001):
    if str(num) == str(num)[::-1]:
        print(num)

Again, these exercises will help you get a grip on loops and conditions and along the way provide more coding experience. Keep up with There are always different variations and challenges to keep growing your Python skills.

Conclusion

This large set of practices will make you feel more comfortable in writing Python programs using basic control flow techniques such as if-else and for loops. From basic calculations to elaborate logic, these problems will cement your thinking process so you are better equipped next time. You should at least study and learn these concepts… otherwise you will have very little chance of understanding anything to do with Python, although I can say that mastering them creates a good foundation for moving on up in more advanced topics within the Python world which ends there: designing real-life software. Practice and learn more Python programming techniques.

For Loop Example in Python

Leave a Comment