Class Notes on Loops in Python
Introduction: Why Loops?
In everyday life, we often need to repeat tasks multiple times. Consider these examples:
- Multiplying a number from 1 to 10 to create a table.
- Calculating factorial by multiplying a number from n down to 1.
- Repeating daily tasks like preparing your school bag or attending school.
Pseudocode Example of Repetition (Multiplying Table)
- Step 1: Start
- Step 2: Input number n to print its table
- Step 3: Set count = 1
- Step 4: Display n * count
- Step 5: Increment count by 1
- Step 6: If count == 10, stop
- Step 7: Else, repeat from Step 4
- Step 8: Stop
Python Loops
Python provides two types of loops to handle repetition:
- While Loop (Conditional loop)
- For Loop (Counting loop)
Understanding range()
Function
The range()
function is often used with the for loop to repeat a task a certain number of times.
- Syntax:
range(lower_limit, upper_limit)
This generates values from lower_limit to upper_limit – 1.
Examples:
range(1, 10)
→ generates numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9]range(0, 7)
→ generates numbers: [0, 1, 2, 3, 4, 5, 6]
By default, the step value is 1. You can also specify a different step:
range(1, 10, 2)
→ generates: [1, 3, 5, 7, 9]
You can even use a negative step to generate numbers in reverse:
range(10, 0, -1)
→ generates: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Using in
and not in
in Python
The operators in
and not in
are used in loops to check whether a value is present in a range or a list.
Examples:
>>> 5 in [1, 2, 3, 4, 5] # True
>>> 5 in [1, 2, 3, 4] # False
>>> 'a' in 'apple' # True
>>> 'national' in 'international' # True
Program Example: Check if a Word is Part of a Sentence
line = input("Enter a statement: ")
word = input("Enter a word: ")
if word in line:
print(f"Yes, '{word}' is a part of '{line}'")
else:
print(f"No, '{word}' is not a part of '{line}'")
For Loop in Python
A for loop in Python processes items in any sequence like a list, tuple, dictionary, or string. It can also repeat a task a fixed number of times using the range()
function.
Examples:
# For loop with a list
School = ["Principal", "PGT", "TGT", "PRT"]
for sm in School:
print(sm)
# For loop with a tuple
Code = (10, 20, 30, 40, 50, 60)
for cd in Code:
print(cd)
Printing Natural Numbers from 1 to 100:
for i in range(1, 101):
print(i, end='\t')
Multiplication Table Program:
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Sum of Numbers Divisible by 7 (Between 1 and 100):
sum = 0
for i in range(1, 101):
if i % 7 == 0:
sum += i
print("Sum of numbers divisible by 7 is:", sum)
While Loop in Python
The while loop is a conditional loop that repeats as long as the condition remains True. It checks the condition first, then enters the loop if the condition is true.
Components of a While Loop:
- Initialization: Starting value of the loop variable.
- Test Condition: Loop continues until this condition becomes false.
- Body of the Loop: Statements to execute repeatedly.
- Update Statement: Updates loop variables for the next iteration.
Example:
i = 1
while i <= 10:
print(i)
i += 1
Practice Questions:
- Write a program to enter a number and find its factorial.
- Write a program to print the Fibonacci series up to n terms.
- Write a program to enter 10 numbers and find their sum and average.
- Write a program to enter a range (Lower_Limit, Upper_Limit) and find the sum of all odd and even numbers within the range.
Convert for
Loop Programs to while
Loop
Example (Multiplication Table with While Loop):
num = int(input("Enter a number: "))
i = 1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
Break and Continue Statements in Loops
- Break: Terminates the loop when a specific condition is met.
- Continue: Skips the current iteration and moves to the next iteration.
Example – Break Statement:
for i in range(1, 20):
if i % 6 == 0:
break
print(i)
Output:
1
2
3
4
5
Example – Continue Statement:
for i in range(1, 20):
if i % 6 == 0:
continue
print(i, end=' ')
Output:
1 2 3 4 5 7 8 9 10 11 13 14 15 16 17 19
Else Clause with Loops
Both for
and while
loops in Python can have an else clause. It runs only when the loop terminates normally (not using break).
Example:
i = 1
while i <= 10:
print(i)
i += 1
else:
print("Loop Over")
Random Number Generation
Python allows generating random numbers using the random
library:
import random
print(random.randint(1, 10)) # Generates a random number between 1 and 10
These notes introduce you to the basic concepts of loops, covering both for and while loops in Python, with practical examples to solidify your understanding. Happy coding!