Here are 45 Python exercises on loops (for, while), if-else statements, and the range() function, along with their solutions. Each exercise comes with a brief description of the problem and a solution that utilizes the mentioned constructs.
Python Exercises on Loops, Conditions, and Range() Function
If you already have learned the basics of Python programming, then it’s time to invest your efforts in some coding practice. Go through the below Python questions and try to first solve by yourself. Take help from here either you are stuck or compare your code. Maybe, you did it in a better way than we did. That’s why our goal is to make you a better programmer.
Also Check: 40 Python Exercises for Beginners
If-Else Statements
Decision-making is the most basic but important piece of any programming language. Python if else construct is a powerful and extensible tool that you must master. Hence, face the below questions, these are few but should be good enough for practice. You’ll, however, see more mixed questions ahead.
Exercise #1
Problem: Check if a given number is even or odd.
Context: We’ll use an if-else statement to check whether a given number is even or odd. The modulo operator (%
) is used to determine if the number is divisible by 2.
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
Exercise #2
Problem: Determine if a person is eligible to vote based on their age.
Context: Using an if-else statement, we’ll check if a person’s age is greater than or equal to 18 to determine eligibility to vote.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Exercise #3
Problem: Test if a value is greater or less than zero, or equal to zero.
Context: We’ll use if-elif-else statements to classify a given number as greater or less than zero, or equal to zero.
num = float(input("Enter the numeric value: "))
if num > 0:
print("The numeric value is positive.")
elif num < 0:
print("The numeric value is negative.")
else:
print("The numeric value is zero.")
Exercise #4
Problem: Determine the largest of three numbers.
Context: Using if-elif-else statements, we’ll compare three numbers and identify the largest among them.
a, b, c = map(int, input("Enter three numbers separated by space: ").split())
if a >= b and a >= c:
print(f"{a} is the largest.")
elif b >= a and b >= c:
print(f"{b} is the largest.")
else:
print(f"{c} is the largest.")
Exercise #5
Problem: Check if a year is a leap year.
Context: We’ll use an if-else statement to determine if a given year is a leap year based on the leap year rule.
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Python Exercises on For Loops
Find some Python exercises on loops like the for loop. Python for loop is the most straightforward mechanism to do any iterative task. Try to solve some of these for your coding practice.
Exercise #6
Problem: Print the elements of a list.
Context: We’ll use a for loop to iterate through each element in a list and print them.
my_list = [1, 2, 3, 4, 5]
for element in my_list:
print(element)
Exercise #7
Problem: Calculate the sum of all elements in a list.
Context: Using a for loop, we’ll iterate through the elements of a list and accumulate their sum.
numbers = [5, 10, 15, 20]
sum_result = 0
for num in numbers:
sum_result += num
print(f"Sum: {sum_result}")
Exercise #8
Problem: Print the multiplication table for a given number.
Context: We’ll use a for loop to iterate through the range and print the multiplication table for a specified number.
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")
Exercise #9
Problem: Print even numbers from 1 to 20.
Context: Using a for loop and the range function, we’ll print even numbers within a specified range.
for i in range(2, 21, 2):
print(i)
Exercise #10
Problem: Calculate the factorial of a number.
Context: Using a for loop, we’ll multiply the numbers from 1 to the given number to calculate its factorial.
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is {factorial}")
Python Exercises on While Loops
Find some Python exercises on loops like the while loop. Python while loop is a programming construct that is somewhat closer to today’s behavioral programming. It lets you write the code like you were speaking to someone.
Exercise #11
Problem: Guess the correct number game.
Context: We’ll use a while loop to repeatedly ask the user to guess a number until they guess it correctly.
import random
target_number = random.randint(1, 10)
guess = 0
while guess != target_number:
guess = int(input("Guess the number (1-10): "))
print("Congratulations! You guessed the correct number.")
Exercise #12
Problem: Sum of numbers until a negative number is encountered.
Context: Using a while loop, we’ll continuously ask the user to input numbers and calculate their sum until a negative number is entered.
sum_result = 0
num = 0
while num >= 0:
num = int(input("Enter a number (negative to stop): "))
if num >= 0:
sum_result += num
print(f"Sum of positive numbers: {sum_result}")
Exercise #13
Problem: Print the Fibonacci sequence up to a certain limit.
Context: Using a while loop, we’ll generate and print Fibonacci numbers until reaching a specified limit.
limit = int(input("Enter the limit for Fibonacci sequence: "))
a, b = 0, 1
while a <= limit:
print(a, end=" ")
a, b = b, a + b
Exercise #14
Problem: Calculate the square root of a number using the Babylonian method.
Context: We’ll use a while loop to iteratively improve an estimate until it converges to the square root of the given number.
num = float(input("Enter a number: "))
guess = num / 2
epsilon = 0.0001
while abs(guess * guess - num) > epsilon:
guess = (guess + num / guess) / 2
print(f"The square root of {num} is approximately {guess}")
Exercise #15
Problem: Reverse a given number.
Context: Using a while loop, we’ll reverse the digits of a given number.
num = int(input("Enter a number: "))
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
print(f"Reversed number: {reversed_num}")
Range() Function
Python range() function is in itself an in-direct list of numbers or iterations. It is a simple yet powerful way to implement repetitive logic. It is inevitable for you to master it to become a better Python programmer. So, make sure you complete every Python exercise given here.
Exercise #16
Problem: Print numbers from 5 to 15 using the range()
function.
Context: We’ll use the range()
function to generate numbers within a specified range and print them.
for i in range(5, 16):
print(i)
Exercise #17
Problem: Print even numbers from 1 to 20 using the range()
function.
Context: We’ll use the range()
function to generate even numbers within a specified range.
for i in range(2, 21, 2):
print(i)
Exercise #18
Problem: Print the squares of numbers from 1 to 10 using the range()
function.
Context: We’ll utilize the range()
function to generate numbers within a specified range and print their squares.
for i in range(1, 11):
print(f"The square of {i} is {i**2}")
Exercise #19
Problem: Calculate the sum of squares from 1 to 5.
Context: Using a for loop and the range()
function, we’ll calculate the sum of squares for a specified range.
sum_squares = 0
for i in range(1, 6):
sum_squares += i**2
print(f"Sum of squares from 1 to 5: {sum_squares}")
Exercise #20
Problem: Check if a number is prime.
Context: We’ll use a for loop and the range()
function to check if a given number is prime.
num = int(input("Enter a number: "))
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime and num > 1:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
More Python Exercises on Loops
Exercise #21
Problem: Calculate the factorial of a number using a while loop.
Context: We’ll use a while loop to multiply numbers from 1 to the given number to calculate its factorial.
n = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= n:
factorial *= i
i += 1
print(f"Factorial of {n} is {factorial}")
Exercise #22
Problem: Find the sum of digits of a given number using a while loop.
Context: Using a while loop, we’ll extract and sum the digits of a given number.
num = int(input("Enter a number: "))
sum_digits = 0
while num > 0:
digit = num % 10
sum_digits += digit
num //= 10
print(f"Sum of digits: {sum_digits}")
Exercise #23
Problem: Generate a random password of a given length.
Context: Using a while loop, we’ll generate a random password of the specified length.
import random
import string
password_length = int(input("Enter the password length: "))
password = ""
while len(password) < password_length:
password += random.choice(string.ascii_letters + string.digits + string.punctuation)
print(f"Generated Password: {password}")
Exercise #24
Problem: Print a pattern using a while loop.
Context: We’ll use a while loop to print a pattern of stars.
rows = int(input("Enter the number of rows: "))
i = 1
while i <= rows:
print("*" * i)
i += 1
Exercise #25
Problem: Calculate the sum of numbers until a non-digit is encountered.
Context: Using a while loop, we’ll continuously ask the user to input numbers and calculate their sum until a non-digit is entered.
sum_result = 0
while True:
try:
num = int(input("Enter a number (non-digit to stop): "))
sum_result += num
except ValueError:
break
print(f"Sum of numbers: {sum_result}")
Some More Python Exercises Using Mixed Constructs
Now, it’s time to solve Python exercises that have a mix of loops, if-else, and range() functions.
Exercise #26
Problem: Print numbers from 10 to 1 in reverse order using the range()
function.
Context: We’ll use the range()
function to generate numbers within a specified range in reverse order.
for i in range(10, 0, -1):
print(i)
Exercise #27
Problem: Print numbers from 1 to 100, but skip multiples of 5 using the range()
function.
Context: Using the range()
function, we’ll print numbers in a specified range, skipping multiples of 5.
for i in range(1, 101):
if i % 5 != 0:
print(i)
Exercise #28
Problem: Print the sum of even numbers from 1 to 50 using the range()
function.
Context: We’ll use the range()
function to generate even numbers within a specified range and calculate their sum.
sum_even = 0
for i in range(2, 51, 2):
sum_even += i
print(f"Sum of even numbers from 1 to 50: {sum_even}")
Exercise #29
Problem: Calculate the product of numbers from 1 to 10 using the range()
function.
Context: Using the range()
function, we’ll calculate the product of numbers within a specified range.
product = 1
for i in range(1, 11):
product *= i
print(f"Product of numbers from 1 to 10: {product}")
Exercise #30
Problem: Print numbers from 1 to 20, but replace multiples of 3 with “Fizz” and multiples of 5 with “Buzz”.
Context: Using the range()
function, we’ll print numbers in a specified range, replacing multiples of 3 with “Fizz” and multiples of 5 with “Buzz”.
for i in range(1, 21):
if i % 3 == 0:
print("Fizz", end=" ")
elif i % 5 == 0:
print("Buzz", end=" ")
else:
print(i, end=" ")
Exercise #31
Problem: Calculate the sum of digits of a number until a single-digit number is obtained.
Context: Using a while loop, we’ll repeatedly sum the digits of a number until a single-digit number is obtained.
num = int(input("Enter a number: "))
while num >= 10:
num = sum(int(digit) for digit in str(num))
print(f"Single-digit sum: {num}")
Exercise #32
Problem: Check if a number is a palindrome.
Context: Using a while loop, we’ll reverse the digits of a number and check if it is the same as the original number.
num = int(input("Enter a number: "))
original_num = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
if original_num == reversed_num:
print(f"{original_num} is a palindrome.")
else:
print(f"{original_num} is not a palindrome.")
Exercise #33
Problem: Find the greatest common divisor (GCD) of two numbers.
Context: Using the Euclidean algorithm, we’ll find the GCD of two given numbers.
def find_gcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
gcd = find_gcd(num1, num2)
print(f"GCD of {num1} and {num2} is {gcd}")
Exercise #34
Problem: Convert a decimal number to binary.
Context: Using a while loop, we’ll convert a decimal number to binary.
decimal_num = int(input("Enter a decimal number: "))
binary_num = ""
while decimal_num > 0:
binary_num = str(decimal_num % 2) + binary_num
decimal_num //= 2
print(f"Binary representation: {binary_num}")
Exercise #35
Problem: Find the factorial of a number using recursion.
Context: We’ll define a recursive function to find the factorial of a given number.
def factorial_recursive(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
num = int(input("Enter a number: "))
result = factorial_recursive(num)
print(f"Factorial of {num} is {result}")
Exercise #36
Problem: Find the sum of natural numbers using recursion.
Context: We’ll define a recursive function to find the sum of natural numbers up to a given limit.
def sum_of_natural_numbers(n):
if n == 0:
return 0
else:
return n + sum_of_natural_numbers(n - 1)
limit = int(input("Enter a limit: "))
result = sum_of_natural_numbers(limit)
print(f"Sum of natural numbers up to {limit} is {result}")
Exercise #37
Problem: Reverse a string using a while loop.
Context: Using a while loop, we’ll reverse the characters of a given string.
input_str = input("Enter a string: ")
reversed_str = ""
index = len(input_str) - 1
while index >= 0:
reversed_str += input_str[index]
index -= 1
print(f"Reversed string: {reversed_str}")
Exercise #38
Problem: Check if a given string is a palindrome.
Context: Using a while loop, we’ll compare the characters of a string from both ends to check if it is a palindrome.
input_str = input("Enter a string: ")
is_palindrome = True
start, end = 0, len(input_str) - 1
while start < end:
if input_str[start] != input_str[end]:
is_palindrome = False
break
start += 1
end -= 1
if is_palindrome:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Exercise #39
Problem: Find the square of a number without using the **
operator.
Context: Using a while loop, we’ll find the square of a given number without using the **
operator.
num = int(input("Enter a number: "))
square = 0
counter = 0
while counter < num:
square += num
counter += 1
print(f"The square of {num} is {square}")
Exercise #40
Problem: Calculate the exponential of a number.
Context: Using a while loop, we’ll calculate the exponential of a number.
base = float(input("Enter the base: "))
exponent = int(input("Enter the exponent: "))
result = 1
counter = 0
while counter < abs(exponent):
result *= base
counter += 1
if exponent < 0:
result = 1 / result
print(f"{base}^{exponent} is {result}")
Exercise #41
Problem: Find the length of a string without using the len()
function.
Context: Using a while loop, we’ll find the length of a given string without using the len()
function.
input_str = input("Enter a string: ")
length = 0
while input_str:
length += 1
input_str = input_str[1:]
print(f"Length of the string is {length}")
Exercise #42
Problem: Calculate the sum of the first n
natural numbers using the formula.
Context: We’ll calculate the sum of the first n
natural numbers using the formula (n * (n + 1)) / 2
.
n = int(input("Enter a number: "))
sum_natural_numbers = (n * (n + 1)) // 2
print(f"Sum of the first {n} natural numbers is {sum_natural_numbers}")
Exercise #43
Problem: Check if a given year is a leap year using a while loop.
Context: Using a while loop, we’ll check if a given year is a leap year based on the leap year rule.
year = int(input("Enter a year: "))
is_leap_year = False
while True:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
is_leap_year = True
break
if is_leap_year:
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Exercise #44
Problem: Generate a list of square numbers up to a specified limit.
Context: Using a while loop, we’ll generate a list of square numbers up to a specified limit.
limit = int(input("Enter a limit: "))
squares_list = []
num = 1
while num**2 <= limit:
squares_list.append(num**2)
num += 1
print(f"Squares up to {limit}: {squares_list}")
Exercise #45
Problem: Implement a simple calculator using a while loop.
Context: Using a while loop, we’ll implement a simple calculator that performs addition, subtraction, multiplication, and division based on user input.
def calc():
print("Simple Calculator")
print("Operations:")
print("1. Addition (+)")
print("2. Subtraction (-)")
print("3. Multiplication (*)")
print("4. Division (/)")
print("5. Exit")
while True:
choice = input("Enter your choice (1-5): ")
if choice == '5':
print("Exiting the calculator. Goodbye!")
break
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if choice == '1':
result = num1 + num2
print(f"Result: {num1} + {num2} = {result}")
elif choice == '2':
result = num1 - num2
print(f"Result: {num1} - {num2} = {result}")
elif choice == '3':
result = num1 * num2
print(f"Result: {num1} * {num2} = {result}")
elif choice == '4':
if num2 != 0:
result = num1 / num2
print(f"Result: {num1} / {num2} = {result}")
else:
print("Error: Division by zero. Please enter a non-zero second number.")
else:
print("Invalid choice. Please enter a number between 1 and 5.")
# Run the calc
calc()
Feel free to adapt the file names and content according to your requirements. To explore more Python exercises, check the table shown below.
Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.
Enjoy coding,
TechBeamers.