For Loops in Python
For Loop
In Python, the for loop is used to iterate over a sequence (e.g., List, String) or other iterable objects like range.
Key Concepts
- Iteration: Repeating a process for each item in a sequence.
- Automation: Automating repetitive tasks efficiently.
Syntax
for var in sequence:
statement
sequence: A collection of objects (e.g., a list).var: Takes items from the sequence one by one.statement: Loop body; executed once for each item in the sequence.- Indentation: Loop body must be indented.
Working with For Loop
Example:
Display "Hello"
Display "Hello"
Display "Hello"
Display "Hello"
Can be automated using a for loop:
for i in range(5):
print("Hello")
range(5)creates a list[0, 1, 2, 3, 4].- The loop repeats five times, displaying "Hello" each time.
The range() Function
Used to iterate over a sequence of numbers.
Syntax:
range(start, stop, step)
start(Optional): Integer specifying the start position (default is 0).stop(Required): Integer specifying the stop position (not included).step(Optional): Integer specifying the incrementation (default is 1).
Examples:
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5, 10)
Output:
[5, 6, 7, 8, 9]
range(100, 50, -10)
Output:
[100, 90, 80, 70, 60]
Program to Print Individual Letters in a String
name = input("Enter a string: ")
x = len(name)
for i in range(x):
print("The Character at {} Index Position = {}" .format(i, name[i]))
- Get a string as user input.
- Use a
forloop withrange()to iterate over the string's elements. len(name)specifies the end value of therange()function.- Print characters along with their index using the
format()method.
Program to Find Unique Vowels in a String
name = input("Enter your name: ")
lower_name = str.lower(name)
vowels = ['a', 'e', 'i', 'o', 'u']
foundvowel = [] # list of vowels found in the name
for i in lower_name:
if i in vowels:
if i not in foundvowel:
foundvowel.append(i)
print("The unique vowels found in the name {} are {}" .format(name, foundvowel))
Explanation:
- Get user input for a name.
- Convert the name to lowercase.
- Create a list of vowels.
- Initialize an empty list
foundvowel. - Iterate through the characters of the name.
- Check if each character is in the
vowelslist. - If True, check if the vowel is already in the
foundvowellist. - If not, append the vowel to the
foundvowellist. - Print the unique vowels found.
The in Operator
- Checks if a specified value is an element of a sequence (string or list).
- Returns a Boolean result (True or False).
- In loops, it fetches the next value in the sequence.
- The
not inoperator checks if a value is not an element in a sequence.
Prime Number
- A natural number greater than 1 that is divisible only by 1 and itself.
- Examples: 2, 3, 5, 7, 11, 13, 17, 19, 23, …
Program to Check if a Number is Prime
num = int(input("Enter the number: "))
prime = True
if num <= 1:
prime = False
else:
for i in range(2, num):
if (num % i) == 0:
prime = False
break
if prime:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Nested Loops
A loop inside another loop. The inner loop executes for each iteration of the outer loop.
Program to Print a Pyramid Pattern of Stars
rows = int(input('Enter the number of rows: '))
for i in range(0, rows):
for j in range(0, i + 1):
print("* ", end=" ")
print()
Explanation:
- Get the number of rows from the user.
- Use an outer
forloop to iterate through each row. - Use a nested
forloop to print stars in each row. - The number of stars increases with each row.
- The
endparameter in theprint()function adds a space after each asterisk.
The end Parameter of print() Function
- By default, the
print()function ends with a newline character. - The
endparameter can be used to change this behavior.
Challenges
Challenge 1
Write a program using a for loop to display the multiplication table of a given number up to 10 times.
Solution:
num = int(input("Enter the number: "))
for i in range(1, 11):
print(num, "X", i, "=", num * i)
Challenge 2
Write a program to find the next 100 leap years. A leap year is exactly divisible by four except for the century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.
Solution:
year = int(input("Enter the Year to be checked: "))
leap = year % 4 == 0 and year % 100 != 0 or year % 100 == 0 and year % 400 == 0
if leap:
print("%d is Leap Year" % year)
print('Next 100 Leap years are')
for i in range(100):
year = year + 4
print(year)
else:
print("%d is Not the Leap Year" % year)
Challenge 3
Write a program to print all the prime numbers between a certain range using a ‘for’ loop. Ask the user to input the upper and lower limit for the range. The program should display the prime numbers within the specified range.
Solution:
print('Enter numbers to find the prime numbers within that range')
lower = int(input("Enter the Lower limit: "))
upper = int(input("Enter the Upper limit: "))
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)