Conditional execution

6. Conditional execution#

6.1. If-else statements#

If statements are used to execute a set of commands only under certain conditions. The syntax is shown below. Note that the commands to be run conditionally are indented with a tab.

x = 1
if x > 0:
    print('x is positive')
    print('another line')
if not x > 0:
    print('x is negative')
print('done')
x is positive
another line
done

A chain of conditions can be created with if, elif and else blocks.

if x > 0:
    print('x is positive')
elif x < 0:
    print('x is negative')
else:
    print('x is zero')
x is positive

Exercise:

Using conditional execution, calculate the absolute value of a number (not using the built-in abs function).

6.2. Exceptions#

Conditional execution - same category as if statements. The code in the try statement is run first. If an error occurs while running that code, the code under the except statement is run instead.

a = 'year'
b = 2022

This gives an error, because strings cannot be combined with numbers. Execution of the program is stopped.

a+b
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[4], line 1
----> 1 a+b

TypeError: can only concatenate str (not "int") to str

This tries the same code, and converts both variables to a string if an error occurs. Execution of the program continues.

try:
    combined = a+b
except TypeError:
    combined = str(a)+str(b)
   
print(combined)
year2022