Chapter 3: If statements

If you try, you will learn

face Josiah Wang

Now, let us test whether you really understand using if/if-else statements!

Try to predict the output for the code snippets below.

1 2 3 4 5

Question 1

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

if 8 < 5:
    print("Yes")
Blank

Question 2

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

if 8 < 5:
    print("Yes")
else:
    print("No")
No

Question 3

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

age = 50
if age <= 50:
    print("Young")
else:
    print("Wise")
Young

Question 4

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

coins = 5
if coins < 2:
    coins = coins + 2
print(coins)

Bonus activity: Can you explain (in plain English) what this code is trying to do? Try explaining it to a rubber duck or equivalent.

5
Explanation:

This piece of code adds 2 coins to your coins if you have fewer than 2 coins. Otherwise it does nothing. It will print the number of coins you have at the end of the program.

Question 5

What does the following code snippet output? Type Blank if the code does not output anything, and Error if it produces an error.

if 5:
    print("Yes")
else:
    print("No")
Yes
Explanation:

This piece of code actually works. It is hard to read though, so please do NOT write such codes.

If a condition is not a boolean expression, you can assume that the value of any object is True by default, unless the value is similar to 0 or "empty". For example, if 0: or if "": will evaluate to False. You can check whether an object will evaluate to True or False by using bool(). Try bool(5), bool(-1), bool("love"), bool(""), bool(0), bool(0.0) in an interactive prompt.

This is not important for the course (since I am discouraging you to write like this). But it might be useful to know when you are debugging your code for example! You can read this article if you are interested in understanding this further.