Conditionals

If statements, or conditionals, are useful for doing different things depending on what the values of some expressions are.

For example, suppose we want to print the absolute value of n. If $n \geq 0$, we should print n, and otherwise we should pring -n

The (simplified) format of the if statement is:

if <condition>: <block1> else: <block2> Note that the columns and the tabs before the blocks are mandatory!

If the condition is True, <block1> is executed, and otherwise <block2> is executed.

In our case, the condition is n >= 0

In [1]:
n = -5
if n >= 0:
    print(n)
else:
    print(-n)
5

Let's now write a more complicated grade adjustment program: we'll adjust the grade by 20 if it's at or above 70, and we'll adjust it by 19 if it's below 70.

In [2]:
exam_grade = 60
engsci_adjustment = 20
ece_adjustment = 19
if exam_grade >= 70:
    exam_grade = exam_grade - engsci_adjustment
else:
    exam_grade = exam_grade - ece_adjustment

print(exam_grade)
41

More complicated conditionals

Suppose we have more than two outcomes. Let's say that you bet your friend that you'll get a 98 on the exam, and let's say that you want to print "I am happy" if you got a grade of 99 or 100. Otherwise, you want to print the frownie emoticon.

Here is how we can set this up. The general format is:

if <condition1>: <block1> elif <condition2>: <block2> elif <condition3>: <block3> . . . else: <blockn>

Python will keep checking the conditions in order until one is True, and will execute the corresponding block. If no condition is True, Python will execute the block under else (blockn)

Note: the tabs and columns are all mandatory, and the format has to be exactly right!

In [3]:
exam_grade = 99

if exam_grade == 98:
    print('I won the bet!')
    print('I am happy')
elif exam_grade > 98:
    print('I am happy')
else:
    print(')-:')
    
    
print('At least I am not an artsci')
I am happy
At least I am not an artsci