Iterative Loops
in
Python
What are Iterative Loops?
• Iterative loops are a way to repeat a block of code
multiple times.
• Instead of writing the same code again and again, loops
automate this repetition.
• Python mainly has two types of loops for iteration:
✓ for loop
✓ while loop
for loop
Real Life Example: Attending Classes
Real-life
What this situation:
for loop does:
You have classes from Monday to Friday, and every day,
•It goes through the list of days one by one.
you:
•For
•Wake each
up day, it performs the same action: “Wake up and attend
•Get ready
class.”
•Attend
•Once it the classwith Friday, the loop ends — just like your
finishes
•Take
schoolnotes
week ends.
You repeat these same steps each weekday.
Structure of for loop
Keyword variable Built-in Function
Indentation Block inside
for loop
for loop: Example
Output:
2
3
for i in range(2, 7): 4
print(i) 5
6
• range(start, stop): Generates numbers from start to stop-1.
• Automatic step size: 1
for loop: Example
Output:
7
6
for i in range(7,2,-1): 5
print(i) 4
3
range(7,2,-1): Generates numbers from 7 up to 3, decrementing,
by step=-1 in each iteration.
for loop: Example
Output:
0
2
for i in range(0,10,2): 4
print(i) 6
8
range(0,10,2): Generates numbers from 0 up to 9, incrementing
by step=2 in each iteration.
for loop: Example
Output:
0
1
for i in range(5): 2
print(i) 3
4
• range(n) generates numbers from 0 to n-1
Flowchart
It is a diagram Flowchart Symbols
which visually
presents the
logical flow of
data through
processing
systems from
the beginning
to the end.
Write a Python program to print sum of n
integers (using for loop).
# Input
n = int(input("Enter a positive integer: "))
# Initialize sum
s=0
Output:
# Loop from 1 to n and add each number Enter a positive integer: 10
for i in range(1, n + 1): Sum: 55
s=s+i
Indentation
# Output
print("Sum: ", s)
flowchart
Write a program in Python to calculate
the factorial of a number.
n = int(input("Enter a number: "))
f=1
for i in range(1, n + 1):
f *= i
print("Factorial of", n, "is", f) Output:
Enter a number: 5
Factorial of 5 is 120
Indentation
Enter a number: 0
Factorial of 0 is 1.
Write a program in Python to calculate
the factors of numbers..
# Input
n = int(input("Enter a number: "))
print("Factors:")
for i in range(1, n + 1):
if n % i == 0: Output:
print(i) Enter a number: 10
Factors:
Indentation 1
2
5
10
Write a program in Python to print the
first 6 terms of a geometric sequence
starting with 2 and having a common
ratio of 3.
a=2 # first term
r=3 # common ratio
# Number of terms
n =int(input("Enter a number: "))
print("First", n, "terms of theOutput:
geometric sequence:")
for i in range(n): Enter a number: 6
term = a * (r ** i) First 6 terms of the geometric sequence:
print(term) 2
6
18
54
162
486
Write a program in Python that prompts
the user to input a number and prints its
multiplication table.
n = int(input("Enter a number: "))
Output:
print(f"\n Multiplication Table of {n}:\n")
Enter a number: 4
for i in range(1, 11): Multiplication Table of 4:
print(f"{n} x {i} = {n * i}") 4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
f-string 4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
What is an f-string in Python?
An f-string is short for formatted string literal.
Syntax: f"some text {expression} more text"
• Anything inside {} is evaluated as a Python expression.
• The result is inserted into the string at that position.
Write a program in Python to calculate
the Fibonacci sequence till a specific no.
of terms (Using for loop)
n = int(input("Enter the number of terms: "))
a=0
b=1
for i in range(n):
print(a, end=" ")
temp = a + b
a=b
b = temp Indentation
Output:
Enter the number of terms: 10
0 1 1 2 3 5 8 13 21 34
Structure of while loop
Keyword
Block inside
Indentation
for loop
while loop: Example
i = 0 # Initialization: Start from 0
while i < 5: # Condition: Loop as long as i is less than 5
print(i) # Body: Perform desired action
i += 1 # Increment: Increase i by 1 in each iteration
Output:
0
1
Indentation
2
3
4
Write a Python program to print sum of n
integers (using while loop).
# Input
n = int(input("Enter a positive integer: "))
# Initialize sum
s=0
i=1 Output:
# Loop from 1 to n and add each number Enter a positive integer: 10
while i <= n: Sum: 55
s=s+i
i=i+1
Indentation
# Output
print("Sum: ", s)
Write a program in Python to calculate
the Fibonacci sequence till a specific no.
of terms (Using while loop)
n = int(input("Enter the number of terms: "))
a=0
b=1
i=0
while i<n:
print(a, end=" ")
temp = a + b Indentation
a=b
b = temp
i+=1
Write a program in Python to reverse
a given number
n= int(input("Enter a number: "))
# Initialize reversed number to 0
rev= 0
# Store original number for display
org = n
# Reverse the number using a loop Output:
while n != 0: Enter a number: 123
d = n % 10 Original number: 123
rev = rev * 10 + d Reversed number: 321
n = n // 10 Indentation
print(“Original number:",org)
print("Reversed number:",rev)
Write a program in Python to check if
a number is a palindrome.
# Check if original and reversed are the same
if org == rev:
print(org, "is a palindrome.")
else:
print(org, "is not a palindrome.")
Indentation
Output:
Enter a number: 1221
Reversed number: 1221
1221 is a palindrome.
Write a program in Python to find the
sum of digits of a number
n= int(input("Enter a number: "))
# Initialize
s= 0
while n != 0:
d = n % 10
s+ = d Output:
n = n // 10 Indentation
Enter a number: 123
print(“Sum of digits:",s) Sum of digits: 6
Write a program in Python to check if
a number is an Armstrong number.
n = int(input("Enter a number: "))
# Store the original number
org = n
# Find the number of digits
count = 0
temp = n
while temp > 0:
temp = temp // 10
count += 1
# Calculate the sum of digits raised to the power count
sum_of_powers = 0
temp = n
while temp > 0:
digit = temp % 10
sum_of_powers += digit ** count
temp = temp // 10
# Check and output the result
if sum_of_powers == org:
print(org, "is an Armstrong number.")
else:
print(org, "is not an Armstrong Output:
number.") Enter a number: 1634
1634 is an Armstrong number.
Enter a number: 100
100 is not an Armstrong number.
Enter a number: 153
153 is an Armstrong number.
Write a program in Python to check if
a number is Krishnamurthy number.
import math
n = int(input("Enter a number: "))
# Store the original number Output:
org = n Enter a number: 145
# Initialize sum of factorials 145 is a Krishnamurthy number.
sum_of_factorials = 0
# Calculate the sum of the factorials ofEnter
digitsa number: 1000
while n > 0: 1000 is not a Krishnamurthy number.
digit = n % 10
sum_of_factorials += math.factorial(digit)
n = n // 10
# Check and output the result
if sum_of_factorials == org:
print(org, "is a Krishnamurthy number.")
else:
print(org, "is not a Krishnamurthy number.")
Write a program in Python to convert
a decimal number to a binary
number.
dec = int(input("Enter a decimal number: "))
if dec == 0: Output:
print("Binary: 0") Enter a decimal number: 13
else: Binary of 13 is: 1101
bin = 0
place = 1 # to position the digits correctly
temp = dec Example: Convert 13 to binary
while temp > 0: •Step 1: 13 % 2 = 1, bin = 1, place = 1
rem = temp % 2•Step 2: 6 % 2 = 0, bin = 1 + 0×10 = 1, place = 10
bin += rem * place
•Step 3: 3 % 2 = 1, bin = 1 + 1×100 = 101, place = 100
place *= 10 •Step 4: 1 % 2 = 1, bin = 101 + 1×1000 = 1101
temp = temp // 2
print("Binary of", dec, "is:", bin)
Write a program in Python to enter a
base number and an exponent, and
then calculates the power of the base
to the exponent. The program should
not use the exponentiation operator
(**) or the math.pow() function.
base = int(input("Enter the base number: "))
exp = int(input("Enter the exponent: "))
# Initialize the result variable
res = 1 Output:
# Calculate the power Enter the base number: 2
if exp >= 0: Enter the exponent: 0
for i in range(exp): 2 raised to the power of 0 is: 1
res *= base
else:
for i in range(exp,0): Enter the base number: 5
res /= base Enter the exponent: -3
5 raised to the power of -3 is: 0.008
# Print the result
print(base, "raised to the power of", exp, "is:", res)
Nested Loops
• means a loop statement inside another Syntax
loop statement.
• The complete "inner loop" will be
Outer_loop
executed one time for each iteration of
the "outer loop“.
Inner_loop
• Any number of loops can be defined
inside another loop, i.e., there is no
// inner loop statements.
restriction for defining any number of
loops.
// outer loop statements.
• You can define any type of loop inside
Indentation
another loop; for example, you can
define 'while' loop inside a 'for' loop.
Pattern Generation
n=int(input("Enter no stars:"))
for i in range(n):
print('*',end=‘ ')
Output:
Enter no stars:5
*****
end='' ensures all stars are printed on the
same line without spaces or newlines.
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, n + 1): # Inner loop for how many stars will be printed
print("*", end='')
print() Indentation
After the inner loop completes, print() without arguments
moves to the next line.
What end=‘ ’ Does
print("*", end=‘’) Two Single
Quotations
•After the inner loop completes, print() without arguments
moves to the next line.
Forget to write print().
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, n + 1): # Inner loop for how many stars will be printed
print("*", end='')
Indentation
Write print(“\n”) instead of print()
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, n + 1): # Inner loop for how many stars will be printed
print("*", end='')
print(“\n”) Indentation
Write print() inside Inner(j) Loop
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, n + 1): # Inner loop for how many stars will be printed
print("*", end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many stars will be printed
print("*", end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many stars will be printed
print("*", end=“ ”)
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how numbers will be printed
print(i, end='')
print() Indentation
What end=" " Does
print("*", end=" ")
•Prints * followed by a space.
•This allows multiple prints to appear on the same line
separated by spaces.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many stars will be printed
print(j, end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how characters will be printed
print(chr(64 + i), end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how characters will be printed
print(chr(64 + j), end='')
print() Indentation
Write a program to print following pattern.
Inverted Pattern
n = int(input("Enter number of lines: "))
for i in range(n, 0, -1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many stars will be printed
print(“*”, end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(n, 0, -1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many stars will be printed
print(“*”, end=“ ”)
print()
Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n+1): # Outer loop for Number of lines
for j in range(1, n + 1): # Inner loop
if i == 1 or i == n or j == 1 or j == n : # Print star only on borders
print("*", end=" ")
else:
print(" ", end=" ") # Print space inside
print()
Right-Angled Triangle Pattern Pyramid Pattern
Inverted Right-Angled Inverted Pyramid Pattern
Triangle Pattern
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end=‘ ')
for k in range(1, 2 * i): # Inner loop for stars
print("*", end=‘ ')
print() Indentation
Printing Spaces
for j in range(n - i): •Controls spaces before the stars to center-align
the pyramid.
print(" ", end=‘ ') •The number of spaces decreases as the line
number increases.
i(line) Spaces = n-i
1 3
2 2
3 1
4 0
Printing Stars
for k in range(1, 2 * i): •Prints stars for each line.
•Formula 2*i - 1 gives the number of stars in
print("*", end=‘ ') that line (odd numbers).
i(line) Spaces = n-i
1 1
2 3
3 5
4 7
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
for i in range(n, 0,-1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end='')
for k in range(1, 2 * i): # Inner loop for stars
print("*", end='')
print() Indentation
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
#Upper Half
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end='')
for k in range(1, 2 * i): # Inner loop for stars
print("*", end='')
print()
#Lower Half
for i in range(n-1, 0,-1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end='')
for k in range(1, 2 * i): # Inner loop for stars
print("*", end='')
print()
Write a program to print following pattern.
n = int(input("Enter number of lines: "))
#Upper Half
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end='')
for k in range(1, 2 * i): # Inner loop for stars
print(k, end='')
print()
#Lower Half
for i in range(n-1, 0,-1): # Outer loop for Number of lines
for j in range(n - i): # Inner loop for spaces
print(" ", end='')
for k in range(1, 2 * i): # Inner loop for stars
print(k, end='')
print()
Write a program to print following pattern.
Floyd's triangle
n = int(input("Enter number of lines: "))
a=1
for i in range(1, n + 1): # Outer loop for Number of lines
for j in range(1, i + 1): # Inner loop for how many numbers will be printed
print(a, end=" ") # Print numbers in sequence
a+=1
print()
Write a program to print following pattern.
Palindromic
Pyramid Pattern
n = int(input("Enter number of lines: "))
for i in range(1, n + 1): # Outer loop for number of lines
for j in range(1, n - i + 1):# Print spaces
print(" ", end="")
for k in range(1, i + 1):# Print increasing numbers
print(k, end="")
for k in range(i - 1, 0, -1):# Print decreasing numbers
print(k, end="")
print() # Move to next line
Write a program to print following pattern.
Pascal’s triangle
n = int(input("Enter number of lines: "))
for i in range(n ): # Outer loop for lines
a=1
for j in range(n - i): # Inner loop for spaces
print(" ", end=" ")
for k in range(i + 1): # Inner loop for numbers
print(a, end=" ")
a = a * (i - k) // (k + 1) # Calculate Pascal's number
print()
break Statement in Python
What does break do?
The break statement is used to exit a loop early, before it has
gone
•It through allstops
immediately its iterations.
the loop where it’s used.
•The program continues with the next line after the loop.
Syntax
•Can be used in both for and while loops.
for item in iterable: while condition:
if condition: if condition_to_stop:
break # exits the loop break
break statement with for loop: Example
for i in range(1, 10):
if i == 5: Output:
break 1
2
print(i)
3
4
break statement with while loop: Example
i = 1 # Initialization: Start from 1
while i < 10: # Condition: Loop as long as i is less than 10
if i == 6:
break
print(i) Output:
i += 1 1
2
3
4
5
Write a program in Python to check a
number is prime number or not.
# Input
n = int(input("Enter a positive integer: "))
# Check if the number is less than 2 Output:
if n < 2:
Enter a number: 23
print(n, "is not a prime number.")
else: 23 is a prime number.
for i in range(2, (n//2)+1):
if n % i == 0: Enter a number: 51
print(n, "is not a prime number.") 51 is not a prime number.
break
else:
# This else belongs to the for-loop (executes only if no break occurs)
print(n, "is a prime number.")
WAPP to sum of the alternating harmonic
series up to 𝑛 terms:
n = int(input("Enter a positive integer n: "))
s=0
for k in range(1, n + 1):
s=s+((-1)**(k-1)) / k
print("Sum: ", s)
Output:
Enter a positive integer n: 3
Sum: 0.8333333333333333
WAPP to print the series up to 𝑛 terms:
1,2,6,24,120,720 …
n = int(input("Enter a positive integer n: "))
a=1
for k in range(1, n + 1):
print(a, end=",")
a=a*(1+k)
Output:
Enter a positive integer n: 7
1,2,6,24,120,720,5040,
Write a python program to add first n
terms of the following series:
n = int(input("Enter a positive integer n: "))
a=1
for k in range(1, n + 1):
print(a, end=",")
a=a*(1+k)
Output:
Enter a positive integer n: 7
1,2,6,24,120,720,5040,
n = int(input("Enter number of terms: "))
s=0
f=1
for i in range(1, n+1):
f=f*i # compute factorial iteratively
s=s+ i / f # compute sum of series iteratively
print("Sum:", s)
Output:
Enter number of terms: 3
Sum: 2.5
WAPP to find HCF (GCD) of two numbers
What is HCF?
HCF (Highest Common Factor) is the greatest factor present
in between given two or more given numbers. HCF is also
known as GCD (Greatest Common Divisor) or GCF (Greatest
Common Factor)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
smaller = b
else:
smaller = a
for i in range(1, smaller + 1):
Output:
if (a % i == 0) and (b % i == 0):
Enter first number: 12
hcf = i
Enter second number: 30
HCF: 6
print("HCF:", hcf)
WAPP to find LCM of two numbers
What is LCM?
LCM (Lowest or least Common Multiple) is a smallest positive
integer which is exactly divisible by two or more input numbers.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if a > b:
smaller = b
else:
smaller = a Output:
for i in range(1, smaller + 1): Enter first number: 12
if (a % i == 0) and (b % i == 0): Enter second number: 30
hcf = i HCF: 6
print("HCF:", hcf) LCM: 60
lcm = (a * b) // hcf
print("LCM:", lcm)
Print the pattern up to N lines:
a=1
n=3
# Top row
for i in range(1, n + 1): # 1 2 3
print(a, end=" ")
a += 1
print() Output:
# Middle row
print(a + 4, a + 5, a, sep=" ") # 8 9 4
a += 1 # Now a = 4
# Bottom row
for i in range(7, 4, -1): # 7 6 5
print(i, end=" ")