Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Summary

In this lesson, you learned that:

  • The if statement runs its block of code only if its condition is true. The line with if ends 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.
  • else adds a second branch, which runs when the condition is false, and elif adds 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, True or False, which you can print, store in a variable and use as a condition.
  • Logical operators combine conditions: and is true when both parts are true, or when at least one is, and not turns True into False and back. Parentheses group conditions; without them, and goes before or.
  • An if statement can be nested in the block of another if. 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. 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 if statement with elif branches that changes price to 0, 80 or 100. With an age of 15, the program prints Ticket price: 80.

  2. 2

    Check the youngest visitors: change age to 4. The program must print Ticket price: 0. If it prints Ticket price: 80, look at the order of your conditions.

Back

15/15

  1. 1. The if Statement
  2. 2. Blocks of Code
  3. 3. The else Branch
  4. 4. Quiz: if and else
  5. 5. Comparison Operators
  6. 6. Quiz: Arranging a Condition
  7. 7. Boolean Values
  8. 8. More Options: elif
  9. 9. Quiz: elif
  10. 10. Logical Operators: and
  11. 11. Quiz: and
  12. 12. Logical Operators: or
  13. 13. Logical Operators: not
  14. 14. Nested Conditions
  15. 15. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.