Understanding For Loop in Python
A for loop is used to repeat a block of code multiple times. It goes through each item in a sequence (like a list, word, or range of numbers).
# Basic For Loop Syntax
for item in sequence:
# code to run
print(item)
Here, item is a variable that takes each value from the sequence one by one.
The keyword in is used to check each element inside a sequence.
For example, when we say for x in fruits:, Python will go one by one through the fruits list.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
# Output:
# apple
# banana
# cherry
The range() function generates a sequence of numbers.
range(n) gives numbers from 0 to n-1.
range(start, stop) gives numbers from start to stop-1.
range(start, stop, step) gives numbers with jumps (step).
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
for i in range(5):
print("Hello")
# Output:
# Hello
# Hello
# Hello
# Hello
# Hello
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(total)
# Output:
# 15
for num in range(10):
if num % 2 == 0:
print(num)
# Output:
# 0
# 2
# 4
# 6
# 8
for num in range(10):
if num % 2 != 0:
print(num)
# Output:
# 1
# 3
# 5
# 7
# 9
for num in range(10):
if num > 5:
print(num)
# Output:
# 6
# 7
# 8
# 9
for num in range(10):
if num % 3 == 0:
print(num)
# Output:
# 0
# 3
# 6
# 9
word = "Python"
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
for num in range(1, 6):
print(num * num)
# Output:
# 1
# 4
# 9
# 16
# 25
for num in range(5, 0, -1):
print(num)
# Output:
# 5
# 4
# 3
# 2
# 1
for i in range(1, 11):
print("2 x", i, "=", 2*i)
# Output:
# 2 x 1 = 2
# 2 x 2 = 4
# ...
# 2 x 10 = 20
for i in range(0, 10, 2):
print(i)
# Output:
# 0
# 2
# 4
# 6
# 8
for i in range(3):
print("Alice")
# Output:
# Alice
# Alice
# Alice
for i in range(1, 6):
print(i)
# Output:
# 1
# 2
# 3
# 4
# 5