Summary
In this lesson, you learned that:
- The
ifstatement runs its block of code only if its condition is true. The line withifends with a colon, and the lines of the block are indented by 4 spaces. The first line that isn't indented is no longer part of the block. elseadds a second branch, which runs when the condition is false, andelifadds more branches with conditions of their own. The program checks the conditions from top to bottom and runs only the first true one, so their order matters.- Comparison operators compare two values:
==,!=,>,<,>=and<=. Two texts are equal only if they match exactly, including upper and lower case. =assigns a value, while==compares.- Every comparison gives a boolean value,
TrueorFalse, which you can print, store in a variable and use as a condition. - Logical operators combine conditions:
andis true when both parts are true,orwhen at least one is, andnotturnsTrueintoFalseand back. Parentheses group conditions; without them,andgoes beforeor. - An
ifstatement can be nested in the block of anotherif. Its blocks are then indented by 4 more spaces.
Next comes a small project, in which you'll try out everything from the first two lessons on your own. Then, in the lesson on lists, you'll learn to store many values in a single variable, such as a shopping list or the scores of a whole class.
Instructions
- 1
Practice: a zoo ticket costs 150. Children under 6 get in for free, children under 18 pay 80, and seniors aged 65 or more pay 100. Above the last line, write an
ifstatement withelifbranches that changespriceto0,80or100. With an age of 15, the program printsTicket price: 80. - 2
Check the youngest visitors: change
ageto4. The program must printTicket price: 0. If it printsTicket price: 80, look at the order of your conditions.