본문 바로가기
Study Note/Python

10. Purpose of 'while' and 'for in'

by jhleeatl 2024. 4. 2.

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.

'Study Note > Python' 카테고리의 다른 글

Python Data Types  (0) 2024.04.25
Lambda function  (0) 2024.04.05
9. Method vs Function / Dictionary vs List  (0) 2024.03.28
8. Function simplification  (0) 2024.03.27
7. F-strings & Try Except  (0) 2024.03.27