Tutorial 3.2 - Control Flow
Loops (for, while) and Iterating through sequences.
1. for Loop:
The for loop is used to iterate over a sequence (like a list, string, or range) and execute a block of code for each element in the sequence.fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
2. for Loop with Range:
You can also use the range() function to generate a sequence of numbers and iterate over it using a for loop.for num in range(1, 6):
print(num)
3. while Loop:
The while loop is used to repeatedly execute a block of code as long as a certain condition remains true.count = 0
while count
print("Count:", count)
count += 1
word = "Python"
4. Iterating Through Strings:
You can use loops to iterate through each character in a string:word = "Python"
for letter in word:
print(letter)
5. Iterating Through Dictionaries:
You can also use loops to iterate through dictionaries, where you'll get the keys by default. If you need both keys and values, you can use the .items() method.person = {"name": "Alice", "age": 30}
for key in person:
print(key, ":", person[key])
for key, value in person.items():
print(key, ":", value)
6. break and continue:
- The break statement is used to exit a loop prematurely when a certain condition is met.
- The continue statement is used to skip the current iteration and proceed to the next one.
for num in range(10):
if num == 5:
break
print(num)
for num in range(10):
if num == 5:
continue
print(num)
Loops are fundamental for automating repetitive tasks and processing collections of data. Whether you're iterating through sequences or executing code conditionally, loops allow your programs to perform tasks efficiently and effectively.
Loops are fundamental for automating repetitive tasks and processing collections of data. Whether you're iterating through sequences or executing code conditionally, loops allow your programs to perform tasks efficiently and effectively.