Intro
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-elsestatements in Python for conditional decision-making - for loop: To iterate over a sequence of elements such as list, string.
- range() function: Using a
forloop withrange(), 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
Exercise 1: Print First 10 natural numbers using while loop
Write python code to print first 10 natural numbers using while loop.
Example
1 2 3 4 5 6 7 8 9 10
Hint:
- Some hint for student
Solution:
# program 1: Print first 10 natural numbers
i = 1
while i <= 10:
print(i)
i += 1
Exercise 2: Print the following pattern
Write python code to print the following pattern
Example
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
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+1times usingforloop andrange()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
jin each iteration of inner loop (jis 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)
- Print Patterns In Python
- Nested loops in Python
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.
Example
If the user entered 10 the output should be 55 (=1+2+3+4+5+6+7+8+9+10)
Enter number 10 Sum is: 55
Hint:
Approach 1: Use for loop and range() function
- Create variable
s = 0to 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 variablen - Run loop
ntimes using for loop and range() function - In each iteration of a loop, add current number (
i) to variables - Use the
print()function to display the variableson screen
Approach 2: Use the built-in function sum(). The sum() function calculates the addition of numbers in the list or range
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: Print multiplication table
Write a program to print multiplication table of a given number.
Example
For example, num = 2 so the output should be
2 4 6 8 10 12 14 16 18 20
Hint:
- Set
n =2 - Use
forloop to iterate the first 10 numbers - In each iteration, multiply 2 by the current number.(
p = n*i) - Print
p
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
Example
Given:
numbers = [12, 75, 150, 180, 145, 525, 50]
Expected output:
75 150 145
Hint:
- Use for loop to iterate each item of a list
- Use
breakstatement to break the loop if the current number is greater than 500 - use
continuestatement move to next number if the current number is greater than 150 - Use n
umber % 5 == 0condition to check if number is divisible by 5 - break and continue in Python
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.
Example
For example, the number is 75869, so the output should be 5.
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
Solution:
num = int(input("Input a number: "))
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.
Example
5 4 3 2 1 4 3 2 1 3 2 1 2 1 1
Hint:
- Set
row = 5because the above pattern contains five rows - create an outer loop to iterate numbers from 1 to 5 using
forloop andrange()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.iis 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
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
Write Python code to print list in reverse order using a loop.
Example
Given
list1 = [10, 20, 30, 40, 50]
Ouput
50 40 30 20 10
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
forloop and reverserange()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
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
Write Python number to display numbers from -10 to -1 using for loop
Example
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Hint:
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.
Example
Given
for i in range(5):
print(i)
Output
0 1 2 3 4 Done!
Hint:
- Same as the
ifstatement, Python allows us to use an else block along withforloop.forloop can have theelseblock, which will be executed when the loop terminates normally. See else block in for loop.
Solution:
for i in range(5):
print(i)
else:
print("Done!")
Exercise 11: 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
Example
Given
# range start = 25 end = 50
Output
Prime numbers between 25 and 50 are: 29 31 37 41 43 47
Hint:
- Some hint for student
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.
Example
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Hint:
- Set
num1 = 0andnum2 =1(first two numbers of the sequence) - Run loop ten times
- In each iteration
- print
num1as the current number of the sequence - Add last two numbers to get the next number
res = num1+ num2 - update values of
num1andnum2. Setnum1=num2andnum2=res
- print
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
Example
Given
5! = 5 × 4 × 3 × 2 × 1 = 120
Output
120
Hint:
- Set variable
factorial =1to store factorial of a given number - Iterate numbers starting from 1 to the given number
nusing for loop andrange()function. (here, the loop will run five times becausenis 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
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
Example
Given:
76542
Expected output:
24567
Solution:
num = int(input())
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: Display elements from a given list present at odd index positions
Use a loop to display elements from a given list present at odd index positions.
Example
Given
my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output
20 40 60 80 100
Hint:
- Use list slicing. Using list slicing, we can access a range of elements from a list
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.
Example
Given
input_number = 6
Ouput
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
Hint:
- Iterate numbers from 1 to
nusing for loop andrange()function - In each iteration of a loop, calculate the cube of a current number (
i) by multiplying itself three times (c = i * i* i)
Solution:
input_number = int(input("Input a number: "))
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
Example
Given:
# number of terms n = 5
Output:
24690
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
Example
* * * * * * * * * * * * * * * * * * * * * * * * *
Hint:
- Split pattern into 2 part: upper and lower.
- Use two for loops. First for loop to print the upper pattern and second for loop to print lower pattern.
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")
Run
