Branching and looping techniques are used in Python to make decisions and control the flow of a program. A good understanding of loops and if-else statements is necessary to write efficient code in Python.
This Python loop exercise contains 22 different coding questions, programs, and challenges to solve using if-else conditions, for
loops, the range()
function, and while
loops.
- code solutions are provided for all questions and tested on Python 3.
- Use Online Code Editor to solve exercise questions.
Refer to the following tutorials to solve this exercise:
- Control flow statements: Use the
if-else
statements in Python for conditional decision-making. - for loop: Iterate over a sequence of elements such as a list or string.
- range() function: Using a for loop with range(), we can repeat an action a specific number of times.
- while loop: To execute a code block repeatedly, as long as the condition is True.
- Break and Continue: To alter the loop’s execution in a particular manner.
- Nested loop: A loop inside another loop is known as a nested loop.
Let us know if you have any alternative solutions. It will help other developers.
Table of contents
- Exercise 1: Print first 10 natural numbers using while loop
- Exercise 2: Print the following pattern
- Exercise 3: Calculate sum of all numbers from 1 to a given number
- Exercise 4: Print multiplication table of a given number
- Exercise 5: Display numbers from a list using a 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: Display a message “Done” after the successful execution of the for loop
- Exercise 11: Print 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 integer number
- Exercise 15: Print 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 a series of a number up to n terms
- Exercise 18: Print the following pattern
- Exercise 19: Print Full Multiplication Table
- Exercise 20: Print the alternate numbers pattern
- Exercise 21: Flatten a nested list using loops
- Exercise 22: Find largest and smallest digit in a number
Exercise 1: Print first 10 natural numbers using while loop
Help: while loop in Python
Expected output:
1
2
3
4
5
6
7
8
9
10
Show Solution
Exercise 2: Print the following pattern
Write a Python code 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:
Show Hint
- Decide on the row count, which is 5, because the pattern contains five rows.
- Run the outer loop 5 times using a
for
loop and therange()
function. - Run the inner loop
i+1
times using afor
loop and therange()
function. - In the first iteration of the outer loop, the inner loop will execute one time.
- In the second iteration of the outer loop, the inner loop will execute two times.
- In the third iteration of the outer loop, the inner loop will execute three times, and so on, until row 5.
- Print the value of
j
in each iteration of the inner loop (j
is the inner loop iterator variable). - Display an empty line at the end of each iteration of the outer loop (an empty line after each row).
Show Solution
Exercise 3: Calculate sum of all numbers from 1 to a given number
Write a Python 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 10 Sum is: 55
Refer:
Show Hint
Approach 1: Use for
loop and range()
function
- Create a variable
s
and initialize it to 0 to store the sum of all numbers. - Use Python 3’s built-in input() function to take input from the user.
- Convert the user’s input to an integer type using the
int()
constructor and save it to a variablen
. - Run loop
n
times using for loop and range() function - In each iteration of the loop, add the current number (
i
) to the variables
. - Use the
print()
function to display the value of the variables
on the screen.
Approach 2: Use the built-in function sum()
. The sum()
function calculates the addition of all numbers from 1 to a given number.
Show Solution
Solution 1: Using for
loop and range()
function
Solution 2: Using the built-in function sum()
n = int(input("Enter number "))
# pass range of numbers to sum() function
x = sum(range(1, n + 1))
print('Sum is:', x)
Code language: Python (python)
Exercise 4: Print multiplication table of a given number
Given:
num = 2
Code language: Python (python)
Expected output is:
2 4 6 8 10 12 14 16 18 20
Show Hint
You can use a simple for
loop to generate the multiplication table for a specific number.
- Set
n = 2
. - Use
for
loop to iterate the first 10 natural numbers (From 1 to 10) - In each iteration, multiply the current number by 2 (
p = n*i
). Now printp
Also See: Create Multiplication Table in Python
Show Solution
Exercise 5: Display numbers from a list using a loop
Write a Python 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 following 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:
75 150 145
Refer: break and continue in Python
Show Hint
- Use a
for
loop to iterate through each item in the list. - Use a
break
statement to exit the loop if the current number is greater than 500. - Use the
continue
statement to skip the current number and move to the next if the current number is greater than 150. - Use the condition
number % 5 == 0
to check if the number is divisible by 5.
Show Solution
Exercise 6: Count the total number of digits in a number
Write a Python 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 a loop
- Reduce the last digit from the number using floor division (
number = number // 10
) - Increment counter by 1
- Reduce the last digit from the number using floor division (
- print counter after loop execution is completed
Show Solution
Exercise 7: Print the following pattern
Write a Python program to print the reverse number pattern using a for
loop.
5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
Refer: Print patterns in Python
Show Hint
- Setting the row value to 5 is crucial, as the pattern we’re working with has five rows.
- Using a
for
loop and therange()
function, create an outer loop that iterates through numbers from 1 to 5. - The outer loop controls the number of iterations of the inner loop. For each outer loop iteration, the number of inner loop iterations is reduced by
i
, the outer loop’s current number. - 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, the inner loop executes five times.
- In the second iteration of the outer loop, the inner loop executes four times.
- In the last iteration of the outer loop, the inner loop will execute only once.
Show Solution
Exercise 8: Print list in reverse order using a loop
Given:
list1 = [10, 20, 30, 40, 50]
Code language: Python (python)
Expected output:
50 40 30 20 10
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 a for loop and
reversed(range())
to iterate through index numbers in reverse order, starting fromlength-1
down to 0. In each iteration,i
will be reduced by 1. - In each iteration, print list items using
list1[i]
.i
is the current value of the index.
Show Solution
Solution 1: Using a reversed()
function and for
loop
Solution 2: Using for loop and the len()
function
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
Exercise 10: Display a message “Done” after the successful execution of the 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:
0 1 2 3 4 Done!
Show Hint
Python allows us to use an else
block with a for
loop like the if
statement. The loop can have the else block, which will be executed when it terminates normally. See else block in for loop.
Show Solution
Exercise 11: Print all prime numbers within a range
Note: A Prime Number is a number that can only be divided by itself and 1 without remainders (e.g., 2, 3, 5, 7, 11)
A Prime Number is a natural number greater than 1 that cannot be made by multiplying other whole numbers.
Examples:
- 6 is not a prime number because it can be made by 2×3 = 6
- 37 is a prime number because no other whole numbers multiply to make it.
Given:
# range
start = 25
end = 50
Code language: Python (python)
Expected output:
Prime numbers between 25 and 50 are: 29 31 37 41 43 47
See: Python Programs to Find Prime Numbers within a Range
Show Hint
Think about what defines a prime number. Then, consider how you can check that property for each number within the given range using a loop. You might need another loop inside to help with the check.
- Iterate through each number in the given range.
- For each number, assume it’s prime initially.
- Check for divisibility from 2 up to the square root of the number.
- If divisible by any number in this range, it’s not prime.
- If the inner loop completes without finding a divisor and the number is greater than 1, then it’s prime.
- Print the numbers identified as prime.
- Remember to handle numbers less than or equal to 1.
Show Solution
Exercise 12: Display Fibonacci series up to 10 terms
Have you ever wondered about the Fibonacci Sequence? It’s a series of numbers in which 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 is 13 + 21 = 34.
Expected output:
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Refer: Generate Fibonacci Series in Python
Show Hint
- Set
num1 = 0
andnum2 = 1
(first two numbers of the sequence) - Run the loop 10 times
- In each iteration
- print
num1
as the current number of the sequence - Add the last two numbers to get the following number
result = num1 + num2
- update values of
num1
andnum2
. Setnum1 = num2
andnum2 = res
ult
- print
Show Solution
Exercise 13: Find the factorial of a given number
Write a Python program to use for
loop to find the factorial of a given number.
The factorial (symbol: !
) means multiplying all numbers from the chosen number down to 1.
For example, a factorial of 5!
is 5 × 4 × 3 × 2 × 1 = 120
Expected output:
120
Show Hint
- Set variable
factorial = 1
to store the factorial of a given number - Iterate numbers starting from 1 to the given number
n
using for loop andrange()
function. (here, the loop will run five times becausen
is 5) - In each iteration, multiply the factorial by the current number and assign it again to a factorial variable (
factorial = factorial *i
) - After the loop completes, print
factorial
Show Solution
Exercise 14: Reverse a integer number
Given:
76542
Expected output:
24567
See: Python Programs to Reverse an Integer Number
Show Hint
- Initialize a variable to store the reversed number (set it to 0 initially).
- Use a
while
loop that continues as long as the original number is greater than 0. - Inside the loop:
- Extract the last digit of the original number using the modulo operator (
% 10
). - Update the reversed number: multiply it by 10 and then add the extracted last digit.
- Update the original number by integer division (
// 10
) to remove the last digit.
- Extract the last digit of the original number using the modulo operator (
- After the loop finishes, the reversed number variable will hold the reversed integer.
Show Solution
Exercise 15: Print 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: The list index always starts at 0
Expected output:
20 40 60 80 100
Show Hint
Use list slicing. List slicing in Python is a powerful way to extract a portion (a sublist) of a list based on a specified range of indices. It allows you to create new lists containing elements from a specific starting point up to (but not including) a specific ending point in the original list.
Show Solution
Exercise 16: Calculate the cube of all numbers from 1 to a given number
Write a Python program to print 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 1 Current Number is : 2 and the cube is 8 Current Number is : 3 and the cube is 27 Current Number is : 4 and the cube is 64 Current Number is : 5 and the cube is 125 Current Number is : 6 and the cube is 216
Show Hint
- Iterate numbers from 1 to
n
usingfor
loop andrange()
function - In each iteration of a loop, calculate the cube of a current number (
i
) by multiplying itself three times (cube = i * i* i)
Show Solution
Exercise 17: Find the sum of a series of a number up to n terms
Write a program to calculate the sum of this series up to n terms. For example, if the number is 2 and the number of terms is 5, then the series will be 2+22+222+2222+22222=2469
Given:
# number of terms
num = 2
terms = 5
Code language: Python (python)
Expected output:
24690
Show Hint
- Initialize a variable
sum
with the base number. - Initialize a variable
current_term
with the base number. - Loop
n-1
times (since the first term is already accounted for in the initialization). - Inside the loop:
- Update
current_term
: multiply it by 10 and add the base number. - Add the updated
current_term
to thesum
.
- Update
- After the loop, the
sum
variable will hold the result.
Show Solution
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. The first loop will print the upper pattern, and the second loop will print the lower pattern.
First Pattern:
* * * * * * * * * * * * * * *
Second Pattern:
* * * * * * * * * *
Show Solution
Exercise 19: Print Full Multiplication Table
The multiplication table from 1 to 10 is a table that shows the products of numbers from 1 to 10.
Write a code to generates a complete multiplication table for numbers 1 through 10.
Given:
multiplication table of: 1
1 2 3 4 5 6 7 8 9 10
multiplication table of: 2
2 4 6 8 10 12 14 16 18 20
multiplication table of: 3
3 6 9 12 15 18 21 24 27 30
...
multiplication table of: 10
10 20 30 40 50 60 70 80 90 100
See: Create Multiplication Table in Python
Show Hint
Use nested loop, where one loop is placed inside another.
- The outer loop iterates through the rows (numbers 1 to 10).
- The inner loop iterates through the columns (numbers 1 to 10) to calculate and display the product of the numbers.
Show Solution
Exercise 20: Print the alternate numbers pattern
Pattern:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Show Hint
You need to use two nested loop inside a single loop.
Think about how the numbers are arranged in each row and how that arrangement changes from one row to the next. Consider these points:
- Row Number: Notice that the behavior of the numbers in a row depends on whether the row number is odd or even.
- Number of Elements per Row: The first row has one number, the second has two, the third has three, and so on. The ith row contains i numbers.
- Odd Rows: In odd-numbered rows (1st, 3rd, 5th, etc.), the numbers are printed in increasing order.
- Even Rows: In even-numbered rows (2nd, 4th, etc.), the numbers are printed in decreasing order.
- Starting Number: You need to keep track of the starting number for each row. Observe how the last number of one row relates to the first number of the next row.
Try to use these observations to build your logic row by row. You’ll likely need a loop that iterates through the rows, and inside that loop, you’ll have different logic based on whether the current row is odd or even.
Show Solution
Exercise 21: Flatten a nested list using loops
Write a program to flatten a nested list using loops.
Given:
nested_list = [1, [2, 3], [4, 5, 6], 7, [8, 9]]
# write function 'flatten_list' to flatten a nested list
flattened = flatten_list(nested_list)
print("Flattened list:", flattened)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Code language: Python (python)
Show Hint
You need to use nested loop ( a loop inside another loop)
- Write Outer Loop:
- Iterates over each element in the input
nested_list
.
- Iterates over each element in the input
- Write Inner Loop:
- Check If the element is a list, iterate through the sublist and append each item to
flat_list
. - Otherwise, append the element directly to
flat_list
.
- Check If the element is a list, iterate through the sublist and append each item to
- After processing all elements, return the flattened list.
See: Python isinstance()
Show Solution
Exercise 22: Find largest and smallest digit in a number
Write a program in Python identifies the digit with the highest value and the digit with the lowest value within that number.
Input:
num1 = 9876543210
num2 = -5082
Code language: Python (python)
Output:
Largest digit in 9876543210: 9
Smallest digit in 987654321: 1
Largest digit in -5082: 8
Smallest digit in -5082: 0
Show Hint
- Get Number and treat the Number as a Sequence of Digits.
- Handle the sign (maybe take the absolute value).
- Convert the (absolute) number to a string.
- Initialize variables to store the largest and smallest digits (perhaps with the first digit of the string converted to an integer).
- Loop through the remaining characters of the string (starting from the second character).
- Inside the loop:
- Convert the current character to an integer.
- Compare it with the current largest and smallest, updating if necessary.
- Return or print the largest and smallest digits.