Counting loops
Repeat with for
- A
forloop repeats code a fixed number of times. - The body of the loop is indented, like an
if. - A loop variable holds a new value on each pass.
for으로 반복하기
for루프는 코드를 고정된 횟수만큼 반복합니다.- 루프 본체는
if처럼 들여쓰기됩니다. - 루프 변수는 각 반복마다 새로운 값을 가집니다.
Counting with range
range(5)gives the numbers0, 1, 2, 3, 4(stops before 5).range(1, 6)gives1, 2, 3, 4, 5(start included, stop not).range(0, 10, 2)counts in steps of 2.
range로 세기
range(5)은 숫자0, 1, 2, 3, 4을 제공합니다 (5보다 앞서 멈춤).range(1, 6)은1, 2, 3, 4, 5을 제공합니다 (시작은 포함, 끝은 제외).range(0, 10, 2)은 단계 2씩 세어갑니다.
for i in range(5):
print(i)
Build a total (accumulator)
- An accumulator is a variable that grows inside a loop.
- Start it at
0before the loop. - Add to it on each pass to build a running total.
총합 만들기 (accumulator)
- 누적 변수는 루프 내부에서 커지는 변수입니다.
- 루프 전에
0로 시작하십시오. - 각 반복마다 더하여 누적 합계를 만듭니다.
total = 0
for n in range(1, 6):
total = total + n
print(total)
In Cambridge pseudocode
- A Python
for … rangeloop is the exam's count-controlledFOR … NEXT.
캐미지아 가위코드에서
- Python의
for … range루프는 시험의 카운트 제어FOR … NEXT에 해당합니다.
Total ← 0
FOR I ← 1 TO 5
Total ← Total + I
NEXT I
OUTPUT Total
Words and a number on one line
- A comma inside
printputs a space between the parts. print("7 x", 1, "=", 7 * 1)prints7 x 1 = 7.+cannot join a number to text. Use the comma, or turn the number into text withstr.
한 줄에 단어와 숫자
print안의 쉼표는 부분 사이에 공백을 넣습니다.print("7 x", 1, "=", 7 * 1)는7 x 1 = 7을 출력한다.+은 숫자를 텍스트에 연결할 수 없습니다. 쉼표를 사용하거나, 숫자를str로 텍스트로 변환하십시오.
Common mistakes
range(n)counts0ton - 1, not1ton.range(a, b)stops beforeb.- The loop body must be indented under the
forline.
흔한 실수
range(n)은0부터n - 1까지 세고,1부터n까지는 세지 않습니다.range(a, b)은b보다 앞서 멈춥니다.- 루프 본체는
for줄 아래에 들여쓰기되어야 합니다.
Now you try
- Use a
forloop withrange(...)in each task. - Press Check answer to test your code.
이제 직접 해보기
- 각 작업마다
for루프와range(...)을 사용하세요. - Answer 확인 버튼을 눌러 코드를 테스트하세요.
A counting loop, pass by pass
A for loop repeats its body; watch the counter and the running total.
Use a for loop to print the numbers 1 to 5, each on its own line.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Use a loop and an accumulator to add up every whole number from 1 to 100. Store the total in total.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Multiply together every whole number from 1 to 5 (that is 1×2×3×4×5). Start product at 1 and store the result there.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Print exactly one line: 7 x 1 = 7. Finish the print that is already started. A comma between the parts prints them with spaces: print("7 x", 1, "=", 7 * 1).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Use a for loop to print the first five lines of the 7 times table: 7 x 1 = 7, 7 x 2 = 14, up to 7 x 5 = 35. The print from the last task is already inside the loop — change the 1 into the loop variable.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.