Conditional execution

Conditional execution

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).

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)
<ipython-input-4-ca730b97bf8a> in <module>
----> 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