Conditions – How to Make your Program Act Based on Input

If it rains, you take your umbrella. If it is sunny, you leave it at home.

How can you make a program perform differently based on input or the state of the program (i.e., the content of the variables).

  • Step 1: Inspect the code below. Makes sense , right? Execute it and see.
  • Step 2: Change the assigned value to variable a, such that the program will print “a is less than 5”
  • Lesson: Conditionals have a structure, which is important.
    • The indented lines after the if “expression”: are only executed if the expression is true.
    • As well as, the indented lines after else: are only executed if the if-expression was false.
  • Step 3: Let us explore some examples of boolean expressions, which can be used in if-statements.
  • Step 4: Change the assignment to variable a, such that the last if-statement is true.
  • Step 5: You can use boolean operators (and and or) to combine. See how they can be used in the example below. Can you guess what the result will be?
  • Lesson: You can combine boolean expressions with the operators and and or.
    • A and B is only true if both A and B are true simultaneously (example, 1 < 2 and 3 == 3)
    • A or B: is true if either A or B are true or both A and B are true (example, 2 < 1 or 3 == 3)
  • Step 6: Change the assignment to variable b, such that only the last if-statement is true.
    • Hint: The second condition in the last if-statement will be true no matter the first (a < b or a > c). Therefore you should find a value to b, such that the comparison with a is false in all three if-statements.
  • Step 7: Look at the example below and guess what the result will be.
  • Lesson: Python is easy to understand. Also, the in operator checks if something is in a list.
  • Step 8: What is elif? Try to read it as else if. Makes sense? Read the code below and see if you can guess the outcome.
  • Step 9: Do the following in the above code.
    • First change the b variable, such that the program writes: b is greater than 20
    • Then change the a variable, such that the program writes: Hello World
  • Step 10: What if you do not want something based on a condition? Well, why not try not in your if-statement.
  • Step 11: Correct the answer in the above code to succeed.
  • Exercise
    • Correct all the variables such that all if-statements evaluate to true.

Leave a Reply