Closure#

Syllabus Week 3: Conditionals#

  • Conditional execution with if statements, keyword if followed by a Boolean expression

  • Controlling scope with indented block

  • Alternative execution with if-else statements, keyword else

  • Chained conditionals with if-elif-else statements, keyword elif

  • Nested conditionals

  • The concept of debugging

  • Debugging with print statement: using print() to trace and understand code execution

  • Identifying errors in code that runs but does not produce the expected output

  • Problem-solving by constructing the correct conditions

Advanced#

Yet another reminder about the material in the Advanced section. The advanced material contains additional topics related to the week’s content. You are not required to read this material, and none of the exercises or exam questions will rely on it.

Advanced 3.1: Non-boolean Conditions#

You have learned that the condition is an expression that can evaluate to Boolean, either True or False.

We usually use conditions that already are Boolean but this is not a requirement. Try running the code below.

var = 3
if var:
    print("Line for True was executed")
else:
    print("Line for False was executed")

Change the value of var to 0, 5.7, and 0.0 and see how the output changes. Try also to change its value to a non-empty string for example 'Some string' and to an empty string ''.

If the condition is not Boolean, Python will try to cast it a Boolean. Run the code below to see how numeric and string values are cast to Boolean.

print(bool(3))
print(bool('Some text'))
print(bool(0))
print(bool(''))

Advanced 3.2: Assignment with Conditional Expressions#

Try this code.

x = 0
y = 5 if x > 2 else 3

The assignment in the second line uses a conditional expression. This single line is equivalent to four lines below.

if x > 2:
    y = 5
else:
    y = 3

Use conditional expression to write a single-line alternative for the examples below. To test your solution, you also need to define the variables x and dinner, and test your solution with different values.

if x >= 0:
    my_value = x * x
else:
    my_value = 0
if dinner == "lasagna":
    my_response = "yummy"
else:
    my_response = "not yummy"

Advanced 3.3: Keyword pass#

A conditional statement has to be followed by the indented line or an indented block of code. Sometimes, you may want to have an empty block of code, for example as a placeholder when you are still working on the code. You might attempt to write something like the code below. Try it.

number = 5
if number < 0:
    # Here I write what happens if the number is negative
elif number == 0:
    # Here I write what happens if the number is zero

Since you are getting an indentation error, we can conclude that writing and indented comment does not count as an indented line or a block. Instead, you can use the keyword pass which does nothing else than making sure that the block is not empty. Try the code below, and see whether it works.

number = 5
if number < 0:
    pass
elif number == 0:
    pass

Advanced 3.4: Multiline Conditions#

Consider the following code.

if month == "December":
    winter = True
elif month == "January":
    winter = True
elif month == "February":
    winter = True
else:
    winter = False

This can also be written as below.

winter = month == "December" or month == "January" or month == "February"

However, with many conditions, the line can become very long and hard to read. To improve readability, you can break the condition into multiple lines as shown below. To indicate that the condition spans multiple lines, you should place the parentheses around the condition.

winter = (month == "December" or 
          month == "January"  or 
          month == "February")

Advanced 3.5: The guessing game#

Can you guess a random number between 1 and 10 in two tries? Try it out by playing the game below.

import random
print(21 * "*~")
print('      WELCOME TO "THE GUESSING GAME"!')
print(21 * "*~")
number = random.randint(1, 10)
guess = int(input("Guess a number between 1 and 10: "))
if guess == number:
    print("You guessed it in the first try!")
else:
    print("No, but you have one try left!")
    guess= int(input("Guess a number between 1 and 10: "))
    if guess == number:
        print("You guessed it in the second try!")
    else:
        print("No, sorry. No more tries left.") 
        print("The number was", number)

Make modifications to the game, such that it gives a more informative feedback if you start by guessing the wrong number. Choose for yourself how much extra information you want to provide, for example:

  • You can reply with Too high or Too low, depending on whether the guess is higher or lower than the random number.

  • You cen reply with You are off by 1, You are off by 2 or Too far depending on whether the absolute difference between the guess and the random number is 1, 2 or larger than 2.