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

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

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

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

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

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

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

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

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

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

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

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

Code language: Python (python)

**Expected output:**

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

## Show Solution

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

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

### Exercise 14: Reverse a given integer number

**Given**:

76542

**Expected output:**

24567

## Show Solution

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

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

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

Code language: Python (python)

**Expected output:**

24690

## 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. First for loop to print the upper pattern and second for loop to print lower pattern

**First Pattern**:

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

**Second Pattern**:

* * * * * * * * * *