Part 3: Python Programming
6. Conditionals
Conditionals
Real programs must make decisions: show a discount only to members, warn when a battery is low, mark an answer right or wrong. Python makes decisions with the if statement, which runs a block of code only when a condition is true.
The basic if statement
Write the keyword if, a condition, and a colon. The code that runs when the condition is true is indented underneath. Indentation (usually four spaces) is how Python knows which lines belong to the block; it is not optional:
else and elif
Add else for what to do when the condition is false, and elif (short for "else if") to test further conditions in order. Python checks each condition from top to bottom and runs the first block whose condition is true, then skips the rest:
Comparison and logical operators
Conditions are built from comparisons that produce True or False. The comparison operators are == (equal), != (not equal), <, >, <=, and >=. Note the double equals for comparison; a single = is assignment. Combine conditions with the logical operators and, or, and not:
and is true only when both sides are true; or is true when at least one side is true; not flips a value.
Truthiness
Every value in Python can be treated as true or false in a condition. Zero, empty strings, empty lists, and None are "falsy"; almost everything else is "truthy". This lets you write natural checks:
Nesting
An if can live inside another if. Increase the indentation for each level, but avoid nesting too deeply because it quickly becomes hard to read:
Conditionals give your programs the power of choice. Practice by writing a program that reads a number and prints whether it is negative, zero, or positive using if, elif, and else.