if

Resources

if

if is one of the basic control flow statements. It allows us to execute some code only if a given condition is met.

If the condition is not met the code inside the if block won’t be executed.

Every line included in the block will be executed, not just the first one.

Fix the following code to print “Done!” even when the condition is not met.

Note

Remember that a block ends when the indentation returns to the previous level.

Note

Fix the following code.

Note

else

It is common that we want to execute some code when the condition is met, and some other code when the condition is not met, for that we use else.

Fix this code:

Tip

Write some code capable of, given a pair of numbers, finding out which is the highest.

Tip

Fix the following code to prevent the error when a = 0.

Tip

elif

elif allows us to test for different conditions sequentialy.

When several conditions are met only the first True one will be executed.

In Python, a more powerful alternative to elif is the match statement.

Write a program that classifies a person into: baby, child, teenager, young, and old

Tip

Write a program that writes the quote of the selected philosopher.

Tip

Boolean casting

When a condition is evaluated, internally the if statement casts anything given to a boolean. So, you will usually see expressions like:

It would be very weird to write:

Remember that everything that we talked about booleans and boolean arithmetic is applicable to the if evaluation.