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**:

**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:**

1 2 3 4 5 6 7 8 9 10

## Show Solution

```
# program 1: Print first 10 natural numbers
i = 1
while i <= 10:
print(i)
i += 1
```

### 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**:

## 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 times
for 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("")
```

### 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 10 Sum is: 55

**Refer**:

## 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 numbers
s = 0
n = 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 += i
print("\n")
print("Sum is: ", s)
```

**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)
```

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

For example, `num = 2`

so the output should be

2 4 6 8 10 12 14 16 18 20

## 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 times
for i in range(1, 11, 1):
# 2 *i (current number)
product = n * i
print(product)
```

### 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]`

**Expected output:**

75 150 145

**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 n
`umber % 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 list
for item in numbers:
if item > 500:
break
elif item > 150:
continue
# check if number is divisible by 5
elif item % 5 == 0:
print(item)
```

### 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

- Reduce the last digit from the number using floor division (
- print counter

## Show Solution

```
num = 75869
count = 0
while num != 0:
# floor division
# to reduce the last digit from number
num = num // 10
# increment counter by 1
count = count + 1
print("Total digits are:", count)
```

### 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 = 5
k = 5
for i in range(0,n+1):
for j in range(k-i,0,-1):
print(j,end=' ')
print()
```

### Exercise 8: Print list in reverse order using a loop

**Given**:

`list1 = [10, 20, 30, 40, 50]`

**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
`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 list
new_list = reversed(list1)
# iterate reversed list
for item in new_list:
print(item)
```

**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 first
size = len(list1) - 1
for i in range(size, -1, -1):
print(list1[i])
```

### 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)
```

### 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)
```

**Expected output:**

0 1 2 3 4 Done!

## Show Hint

Same as the `if`

statement, Python allows us to use an else block along with `for`

loop. `for`

loop can have the `else`

block, which **will 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!")
```

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

**Note**: A Prime Number is a number that cannot be 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**:

```
# range
start = 25
end = 50
```

**Expected output:**

Prime numbers between 25 and 50 are: 29 31 37 41 43 47

## Show Solution

```
start = 25
end = 50
print("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)
```

### 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`

- print

## Show Solution

```
# first two numbers
num1, num2 = 0, 1
print("Fibonacci sequence:")
# run loop 10 times
for 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 = res
```

### 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 = 5
factorial = 1
if 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)
```

### Exercise 14: Reverse a given integer number

**Given**:

76542

**Expected output:**

24567

## Show Solution

```
num = 76542
reverse_number = 0
print("Given Number ", num)
while num > 0:
reminder = num % 10
reverse_number = (reverse_number * 10) + reminder
num = num // 10
print("Revere Number ", reverse_number)
```

### 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]`

**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=" ")
```

### 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 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`

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 = 6
for i in range(1, input_number + 1):
print("Current Number is :", i, " and the cube is", (i * i * i))
```

### 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 terms
n = 5
```

**Expected output:**

24690

## Show Solution

```
n = 5
# first number of sequence
start = 2
sum_seq = 0
# run loop n times
for i in range(0, n):
print(start, end="+")
sum_seq += start
# calculate the next term
start = start * 10 + 2
print("\nSum of above series is:", sum_seq)
```

### 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 = 5
for 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")
```