Python if else, for loop, and range() Exercises with Solutions (2024)

To decide and control the flow of a program, we have branching and looping techniques in Python. A good understanding of loops and if-else statements is necessary to write efficient programs in Python.

This Python loop exercise aims to help Python developers to learn and practice if-else conditions, for loop, range() function, and while loop.

Use the following tutorials to solve this exercise

  • Control flow statements: Use the if-else statements in Python for conditional decision-making
  • for loop: To iterate over a sequence of elements such as list, string.
  • range() function: Using a for loop with range(), we can repeat an action a specific number of times
  • while loop: To repeat a block of code repeatedly, as long as the condition is true.
  • Break and Continue: To alter the loop’s execution in a certain manner.
  • Nested loop: loop inside a loop is known as a nested loop

Also Read:

  • Python Loop Quiz

This Python loop exercise include the following: –

  • It contains 18 programs to solve using if-else statements and looping techniques.
  • Solutions are provided for all questions and tested on Python 3.
  • This exercise is nothing but an assignment to solve, where you can solve and practice different loop programs and challenges.

Let us know if you have any alternative solutions. It will help other developers.

Use Online Code Editor to solve exercise questions.

Table of contents

  • Exercise 1: Print First 10 natural numbers using while loop
  • Exercise 2: Print the following pattern
  • Exercise 3: Calculate the sum of all numbers from 1 to a given number
  • Exercise 4: Write a program to print multiplication table of a given number
  • Exercise 5: Display numbers from a list using loop
  • Exercise 6: Count the total number of digits in a number
  • Exercise 7: Print the following pattern
  • Exercise 8: Print list in reverse order using a loop
  • Exercise 9: Display numbers from -10 to -1 using for loop
  • Exercise 10: Use else block to display a message “Done” after successful execution of for loop
  • Exercise 11: Write a program to display all prime numbers within a range
  • Exercise 12: Display Fibonacci series up to 10 terms
  • Exercise 13: Find the factorial of a given number
  • Exercise 14: Reverse a given integer number
  • Exercise 15: Use a loop to display elements from a given list present at odd index positions
  • Exercise 16: Calculate the cube of all numbers from 1 to a given number
  • Exercise 17: Find the sum of the series upto n terms
  • Exercise 18: Print the following pattern

Exercise 1: Print First 10 natural numbers using while loop

Help: while loop in Python

Expected output:

12345678910
Show Solution
# program 1: Print first 10 natural numbersi = 1while i <= 10: print(i) i += 1Code language: Python (python)

Exercise 2: Print the following pattern

Write a program to print the following number pattern using a loop.

1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Refer:

  • Print Patterns In Python
  • Nested loops in Python
Show Hint
  • Decide the row count, i.e., 5, because the pattern contains five rows
  • Run outer for loop 5 times using for loop and range() function
  • Run inner for loop i+1 times using for loop and range() function
    • In the first iteration of the outer loop, the inner loop will execute 1 time
    • In the second iteration of the outer loop, the inner loop will execute 2 time
    • In the third iteration of the outer loop, the inner loop will execute 3 times, and so on till row 5
  • print the value of j in each iteration of inner loop (j is the the inner loop iterator variable)
  • Display an empty line at the end of each iteration of the outer loop (empty line after each row)
Show Solution
print("Number Pattern ")# Decide the row count. (above pattern contains 5 rows)row = 5# start: 1# stop: row+1 (range never include stop number in result)# step: 1# run loop 5 timesfor i in range(1, row + 1, 1): # Run inner loop i+1 times for j in range(1, i + 1): print(j, end=' ') # empty line after each row print("")Code language: Python (python)

Exercise 3: Calculate the sum of all numbers from 1 to a given number

Write a program to accept a number from a user and calculate the sum of all numbers from 1 to a given number

For example, if the user entered 10 the output should be 55 (1+2+3+4+5+6+7+8+9+10)

Expected Output:

Enter number 10Sum is: 55

Refer:

  • Accept input from user in Python
  • Calculate sum and average in Python
Show Hint

Approach 1: Use for loop and range() function

  • Create variable s = 0 to store the sum of all numbers
  • Use Python 3’s built-in function input() to take input from a user
  • Convert user input to the integer type using the int() constructor and save it to variable n
  • Run loop n times using for loop and range() function
  • In each iteration of a loop, add current number (i) to variable s
  • Use the print() function to display the variable s on screen

Approach 2: Use the built-in function sum(). The sum() function calculates the addition of numbers in the list or range

Show Solution

Solution 1: Using for loop and range() function

# s: store sum of all numberss = 0n = int(input("Enter number "))# run loop n times# stop: n+1 (because range never include stop number in result)for i in range(1, n + 1, 1): # add current number to sum variable s += iprint("\n")print("Sum is: ", s)Code language: Python (python)

Solution 2: Using the built-in function sum()

n = int(input("Enter number "))# pass range of numbers to sum() functionx = sum(range(1, n + 1))print('Sum is:', x)Code language: Python (python)

Exercise 4: Write a program to print multiplication table of a given number

For example, num = 2 so the output should be

2468101214161820
Show Hint
  • Set n =2
  • Use for loop to iterate the first 10 numbers
  • In each iteration, multiply 2 by the current number.( p = n*i)
  • Print p
Show Solution
n = 2# stop: 11 (because range never include stop number in result)# run loop 10 timesfor i in range(1, 11, 1): # 2 *i (current number) product = n * i print(product)Code language: Python (python)

Exercise 5: Display numbers from a list using loop

Write a program to display only those numbers from a list that satisfy the following conditions

  • The number must be divisible by five
  • If the number is greater than 150, then skip it and move to the next number
  • If the number is greater than 500, then stop the loop

Given:

numbers = [12, 75, 150, 180, 145, 525, 50]Code language: Python (python)

Expected output:

75150145

Refer: break and continue in Python

Show Hint
  • Use for loop to iterate each item of a list
  • Use break statement to break the loop if the current number is greater than 500
  • use continue statement move to next number if the current number is greater than 150
  • Use number % 5 == 0 condition to check if number is divisible by 5
Show Solution
numbers = [12, 75, 150, 180, 145, 525, 50]# iterate each item of a listfor item in numbers: if item > 500: break elif item > 150: continue # check if number is divisible by 5 elif item % 5 == 0: print(item)Code language: Python (python)

Exercise 6: Count the total number of digits in a number

Write a program to count the total number of digits in a number using a while loop.

For example, the number is 75869, so the output should be 5.

Show Hint
  • Set counter = 0
  • Run while loop till number != 0
  • In each iteration of loop
    • Reduce the last digit from the number using floor division ( number = number // 10)
    • Increment counter by 1
  • print counter
Show Solution
num = 75869count = 0while num != 0: # floor division # to reduce the last digit from number num = num // 10 # increment counter by 1 count = count + 1print("Total digits are:", count)Code language: Python (python)

Exercise 7: Print the following pattern

Write a program to use for loop to print the following reverse number pattern

5 4 3 2 1 4 3 2 1 3 2 1 2 1 1

Refer: Print patterns in Python

Show Hint
  • Set row = 5 because the above pattern contains five rows
  • create an outer loop to iterate numbers from 1 to 5 using for loop and range() function
  • Create an inner loop inside the outer loop in such a way that in each iteration of the outer loop, the inner loop iteration will be reduced by i. i is the current number of an outer loop
  • In each iteration of the inner loop, print the iterator variable of the inner loop (j)

Note:

  • In the first iteration of the outer loop inner loop execute five times.
  • In the second iteration of the outer loop inner loop execute four times.
  • In the last iteration of the outer loop, the inner loop will execute only once
Show Solution
n = 5k = 5for i in range(0,n+1): for j in range(k-i,0,-1): print(j,end=' ') print()Code language: Python (python)

Exercise 8: Print list in reverse order using a loop

Given:

list1 = [10, 20, 30, 40, 50]Code language: Python (python)

Expected output:

5040302010
Show Hint

Approach 1: Use the built-in function reversed() to reverse the list

Approach 2: Use for loop and the len() function

  • Get the size of a list using the len(list1) function
  • Use for loop and reverse range() to iterate index number in reverse order starting from length-1 to 0. In each iteration, i will be reduced by 1
  • In each iteration, print list item using list1[i]. i is the current value if the index
Show Solution

Solution 1: Using a reversed() function and for loop

list1 = [10, 20, 30, 40, 50]# reverse listnew_list = reversed(list1)# iterate reversed listfor item in new_list: print(item)Code language: Python (python)

Solution 2: Using for loop and the len() function

list1 = [10, 20, 30, 40, 50]# get list size# len(list1) -1: because index start with 0# iterate list in reverse order# star from last item to firstsize = len(list1) - 1for i in range(size, -1, -1): print(list1[i])Code language: Python (python)

Exercise 9: Display numbers from -10 to -1 using for loop

Expected output:

-10-9-8-7-6-5-4-3-2-1

See: Reverse range

Show Solution
for num in range(-10, 0, 1): print(num)Code language: Python (python)

Exercise 10: Use else block to display a message “Done” after successful execution of for loop

For example, the following loop will execute without any error.

Given:

for i in range(5): print(i)Code language: Python (python)

Expected output:

01234Done!
Show Hint

Same as theifstatement, Python allows us to use an else block along with for loop. for loop can have theelseblock, whichwill be executed when the loop terminates normally. See else block in for loop.

Show Solution
for i in range(5): print(i)else: print("Done!")Code language: Python (python)

Exercise 11: Write a program to display all prime numbers within a range

Note: A Prime Number is a number thatcannotbe made by multiplying other whole numbers. A prime number is a natural number greater than 1 that is not a product of two smaller natural numbers

Examples:

  • 6 is not a prime mumber because it can be made by 2×3 = 6
  • 37 is a prime number because no other whole numbers multiply together to make it.

Given:

# rangestart = 25end = 50Code language: Python (python)

Expected output:

Prime numbers between 25 and 50 are:293137414347
Show Solution
start = 25end = 50print("Prime numbers between", start, "and", end, "are:")for num in range(start, end + 1): # all prime numbers are greater than 1 # if number is less than or equal to 1, it is not prime if num > 1: for i in range(2, num): # check for factors if (num % i) == 0: # not a prime number so break inner loop and # look for next number break else: print(num)Code language: Python (python)

Exercise 12: Display Fibonacci series up to 10 terms

The Fibonacci Sequence is a series of numbers. The next number is found by adding up the two numbers before it. The first two numbers are 0 and 1.

For example, 0, 1, 1, 2, 3, 5, 8, 13, 21. The next number in this series above is 13+21 =34.

Expected output:

Fibonacci sequence:0 1 1 2 3 5 8 13 21 34
Show Hint
  • Set num1 = 0 and num2 =1 (first two numbers of the sequence)
  • Run loop ten times
  • In each iteration
    • print num1 as the current number of the sequence
    • Add last two numbers to get the next number res = num1+ num2
    • update values of num1 and num2. Set num1=num2 and num2=res
Show Solution
# first two numbersnum1, num2 = 0, 1print("Fibonacci sequence:")# run loop 10 timesfor i in range(10): # print next number of a series print(num1, end=" ") # add last two numbers to get next number res = num1 + num2 # update values num1 = num2 num2 = resCode language: Python (python)

Exercise 13: Find the factorial of a given number

Write a program to use the loop to find the factorial of a given number.

The factorial (symbol: !) means to multiply all whole numbers from the chosen number down to 1.

For example: calculate the factorial of 5

5! = 5 × 4 × 3 × 2 × 1 = 120

Expected output:

120
Show Hint
  • Set variable factorial =1 to store factorial of a given number
  • Iterate numbers starting from 1 to the given number n using for loop and range() function. (here, the loop will run five times because n is 5)
  • In each iteration, multiply factorial by the current number and assign it again to a factorial variable (factorial = factorial *i)
  • After the loop completes, print factorial
Show Solution
num = 5factorial = 1if num < 0: print("Factorial does not exist for negative numbers")elif num == 0: print("The factorial of 0 is 1")else: # run loop 5 times for i in range(1, num + 1): # multiply factorial by current number factorial = factorial * i print("The factorial of", num, "is", factorial)Code language: Python (python)

Exercise 14: Reverse a given integer number

Given:

76542

Expected output:

24567

Show Solution
num = 76542reverse_number = 0print("Given Number ", num)while num > 0: reminder = num % 10 reverse_number = (reverse_number * 10) + reminder num = num // 10print("Revere Number ", reverse_number)Code language: Python (python)

Exercise 15: Use a loop to display elements from a given list present at odd index positions

Given:

my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]Code language: Python (python)

Note: list index always starts at 0

Expected output:

20 40 60 80 100
Show Hint

Use list slicing. Using list slicing, we can access a range of elements from a list

Show Solution
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]# stat from index 1 with step 2( means 1, 3, 5, an so on)for i in my_list[1::2]: print(i, end=" ")Code language: Python (python)

Exercise 16: Calculate the cube of all numbers from 1 to a given number

Write a program to rint the cube of all numbers from 1 to a given number

Given:

input_number = 6

Expected output:

Current Number is : 1 and the cube is 1Current Number is : 2 and the cube is 8Current Number is : 3 and the cube is 27Current Number is : 4 and the cube is 64Current Number is : 5 and the cube is 125Current Number is : 6 and the cube is 216
Show Hint
  • Iterate numbers from 1 to n using for loop and range() function
  • In each iteration of a loop, calculate the cube of a current number (i) by multiplying itself three times (c = i * i* i)
Show Solution
input_number = 6for i in range(1, input_number + 1): print("Current Number is :", i, " and the cube is", (i * i * i))Code language: Python (python)

Exercise 17: Find the sum of the series upto n terms

Write a program to calculate the sum of series up to n term. For example, if n =5 the series will become 2 + 22 + 222 + 2222 + 22222 = 24690

Given:

# number of termsn = 5Code language: Python (python)

Expected output:

24690
Show Solution
n = 5# first number of sequencestart = 2sum_seq = 0# run loop n timesfor i in range(0, n): print(start, end="+") sum_seq += start # calculate the next term start = start * 10 + 2print("\nSum of above series is:", sum_seq)Code language: Python (python)

Exercise 18: Print the following pattern

Write a program to print the following start pattern using the for loop

* * * * * * * * * * * * * * * * * * * * * * * * *

Refer: Print Patterns In Python

Show Hint

Use two for loops. First for loop to print the upper pattern and second for loop to print lower pattern

First Pattern:

* * * * * * * * * * * * * * * 

Second Pattern:

* * * * * * * * * *
Show Solution
rows = 5for i in range(0, rows): for j in range(0, i + 1): print("*", end=' ') print("\r")for i in range(rows, 0, -1): for j in range(0, i - 1): print("*", end=' ') print("\r")Code language: Python (python)
Python if else, for loop, and range() Exercises with Solutions (2024)
Top Articles
Latest Posts
Article information

Author: Nicola Considine CPA

Last Updated:

Views: 6694

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Nicola Considine CPA

Birthday: 1993-02-26

Address: 3809 Clinton Inlet, East Aleisha, UT 46318-2392

Phone: +2681424145499

Job: Government Technician

Hobby: Calligraphy, Lego building, Worldbuilding, Shooting, Bird watching, Shopping, Cooking

Introduction: My name is Nicola Considine CPA, I am a determined, witty, powerful, brainy, open, smiling, proud person who loves writing and wants to share my knowledge and understanding with you.