학습 자료

Loops: for and while

In programming, we often need to repeat actions — like printing items, summing values, or checking conditions. Loops let us do this efficiently without writing the same line multiple times.

Python offers two main types of loops: for and while.


for Loops

A for loop is used when you want to iterate over a sequence (like a list, string, or range of numbers).

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit)

Explanation

  • fruits is a list.
  • The variable fruit takes one value from the list on each loop.
  • The loop prints a sentence using that value.
  • This repeats three times — once for each fruit.

while Loops

A while loop runs as long as a condition is true.

count = 1 while count <= 3: print("Count is:", count) count += 1

Explanation

  • The loop starts with count = 1.
  • It checks the condition count <= 3. If true, it runs the block.
  • After each loop, count increases by 1.
  • When count becomes 4, the loop stops.

When to Use Each

  • Use a for loop when you have a known set of items.
  • Use a while loop when you have a condition that might change over time.

Next, you’ll learn how to control loop flow using break, continue, and pass.

학습 자료

AI 튜터

디자인

업로드

수업 노트

즐겨찾기

도움말

코드 에디터

코드 실행
코드 생성

실행 결과