7 Python For Loop (1)
7 Python For Loop (1)
The for loop in Python provides the ability to loop over the items of any sequence, such as a list,
tuple or a string.
This loop starts with the for keyword, followed by a variable that represents the current item in the
sequence.
The in keyword links the variable to the sequence you want to iterate over.
A colon (:) is used at the end of the loop header, and the indented block of code beneath it is
executed once for each item in the sequence.
statement(s)
iterating_var is a variable to which the value of each sequence item will be assigned during each
iteration.
Statements represents the block of code that you want to execute repeatedly.
If it's a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the
sequence is assigned to iterating_var variable.
During each iteration, the block of statements is executed with the current value of iterating_var.
After that, the next item in the sequence is assigned to iterating_var, and the loop continues until
the entire sequence is exhausted.
print(char)
numbers = (34,54,67,21,78,97,45,44,80,19)
print (num)
Python for Loop with Lists
numbers = [34,54,67,21,78,97,45,44,80,19]
print (num)
print()
print()
for x in numbers:
print (x)
for x in numbers.items():
print (x)
If a else block is used with a for loop, it is executed only when the for loop terminates normally.
The for loop terminates normally when it completes all its iterations without encountering a break
statement, which allows us to exit the loop when a certain condition is met.
else:
n = len(fruits)
print(num)
print(fruits[num])
n = len(fruits)
print(num)
print(fruits[num])
for i in range(5):
print(i)
word = "Python"
print(letter)
print(i)
print(f"{key}: {value}")
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
for i in range(3):
print(i)
else:
print("Loop completed")