Sikau

Python · Day 4 · about 35 min

Control flow and comprehensions

if, for, while — and building lists in one line.

Blocks without braces

In Python, a line ending with a colon starts a block, and the block is the lines indented under it. There are no braces and no end keyword — indentation *is* the syntax. The standard (PEP 8) is four spaces per level. Mixing indents is an IndentationError, which at least means code always looks exactly as it runs.

Python's loops are also different from C-style languages: for always loops over the items of something — a list, a string, a range of numbers, the lines of a file. There is no for (i = 0; i < n; i++). Today you'll learn those loops and then the comprehension, the Pythonic one-line way to build a collection.

if, for and while

score = 72
if score >= 80:
    print("great")
elif score >= 60:
    print("pass")
else:
    print("try again")

for i in range(3):
    print(i, end=" ")
print()
for i, dish in enumerate(["momo", "chiya"], start=1):
    print(i, dish)

Conditions use the words and, or and not, and comparisons can be chained: 0 <= x < 10. Any value can be a condition thanks to truthiness: 0, 0.0, "", [], {}, set() and None are false, nearly everything else is true. So if items: means "if the list isn't empty". zip(a, b) walks two sequences side by side.

while repeats as long as its condition is true. break leaves a loop early and continue skips to the next round. Loops even have an else that runs only when the loop finished without a break — handy for searches: "for each candidate… break if found; else: not found".

The rest of this lesson

  • Comprehensionsexplain
  • A loop with elsepredict
  • Read a comprehensionorder
  • Index and value togetherfill
  • Loops four wayswrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Python