LimioLearn in Flow
🏆 Đấu trường
Đăng nhậpĐăng ký
← Programming for Data Science

Bạn đang xem thử công khai

Đăng nhập để lưu tiến độ, làm bài tập, thảo luận và nhận phản hồi.

Đăng nhập
Module 1: Fundamentals of Python Programming

Control Flow: Conditionals and Loops

In / Lưu PDF

Control Flow: Conditionals and Loops

Review lesson. A summary of the conditionals and loops part of Module 1, for quick reference and self-checking after units 1.7 → 1.8.

Conditionals

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
  • Python checks from top to bottom and runs the first branch whose condition is true, skipping the remaining branches.
  • else belongs to the nearest if at the same indentation level; pass is a placeholder for a block that has not been written yet.

Loops

NeedUse
Repeat a known number of times, or go through each elementfor
Repeat until the condition becomes falsewhile
Exit the loop completelybreak
Skip the rest of the current iterationcontinue
  • range(start, end, step) stops right before end: range(2, 6) gives 2, 3, 4, 5.
  • An else attached to a loop runs only when the loop is not ended by a break.
  • In a while loop, remember to update the condition variable; otherwise the loop runs forever.

Remember

  • Indentation determines the code block; being off by one level means wrong logic.
  • Count the number of iterations of a loop by tracing the first few iterations by hand on paper.