NEBians
search Sign In Register

Loops & Logic

Lesson 2 of 4 Coding game schedule20 min

Loading simulation…

sports_esportsPlay with the blocks and run your code

flagWhat you'll discover

  • arrow_forwardRepeat code with for loops and range()
  • arrow_forwardBranch with if, elif and else
  • arrow_forwardUse while for loops that run until a condition changes
  • arrow_forwardCombine a loop and a condition to solve Fizz

for and the range trick

Python's for loop walks through a sequence of values: for i in range(1, 11): runs its indented body ten times with i counting 1, 2, 3... up to 10. Watch the famous catch: range stops just BEFORE its end number, so range(1, 11) is needed to reach 10. A third value sets the step — range(10, 0, -1) counts backwards. Everything indented under the for line belongs to the loop; the indentation IS the grammar in Python.

Decisions with if, elif, else

if checks a condition: when true, its indented block runs. elif (short for else-if) offers more checks in order, and else catches everything left over. Python tests them top to bottom and runs only the FIRST match, so order matters: check the biggest mark band first when grading. Conditions use comparisons — ==, !=, <, >=, plus % for remainders. n % 2 == 0 asks "does n divide evenly by 2?" — the classic even-number test you will use in this lesson.

while: loop until

A while loop repeats as long as its condition stays true: countdown = 5, then while countdown > 0: print it and subtract one. Something inside the loop must move toward making the condition false — forget the subtraction and you have an infinite loop that never ends! (Try it here: this playground stops runaway programs automatically and tells you.) Use for when you know how many times to repeat; use while when you only know the stopping condition.

quizCheck your knowledge

1. What numbers does for i in range(1, 5) give?
2. How do you check whether n is even?
3. What happens if a while loop's condition never becomes false?