## 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
else:


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


I am happy