10. Purpose of 'while' and 'for in'
1. `while` loop:
- Executes a block of code repeatedly as long as a specified condition is true.
- The condition is evaluated before each iteration, and if it's true, the loop continues. If it's false, the loop terminates.
- Typically used when the number of iterations is not known beforehand.
For example, the following code prints the numbers from 0 to 9 as long as `num` is less than 10:
num = 0
while num < 10:
print(num)
num += 1
2. `for` loop:
- Iterates over a sequence (e.g., list, tuple, string) and executes a block of code for each element in the sequence.
- Each element of the sequence is accessed sequentially, and the loop continues until all elements have been procesed.
- Used when the number of iterations is known or when iterating over elements in a sequence.
For example, the following code prints each element in the list `my_list`:
my_list = [1, 2, 3, 4, 5]
for num in my_list:
print(num)
In summary, while loops and for loops are different types of loop constructs, and the choice between them depends on the specific requirements of the program.