PythonLesson 5 of 16
Booleans and if, elif, else
A comparison in Python answers True or False. Then if picks which block of code runs, the way you decide whether to take an umbrella.
Key points
- Comparisons: == equal, != not equal, <, >, <=, >=
- and needs both, or needs at least one, not flips the answer
- if and else end with a colon; the code inside is indented 4 spaces
- elif is checked only when the conditions above were false
- Only the first matching branch runs, the rest are skipped
Example
total = 1200is_member = Trueprint(total > 1000)if total >= 1000 and is_member: print("You get 10% off")elif total >= 1000: print("Join the club for 10% off")else: print("No discount yet")The total is over 1000 and the buyer is a member, so the first branch runs. Change is_member to False and run it again.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Write a weather adviser. Below 0 print Wear a warm coat, below 15 print Take a jacket, otherwise T-shirt weather. Then, in a separate if, print Take an umbrella when it's raining.
Output
What your program prints appears here.