Skip to main content

7.5) If... It Rains, Use An Umbrella


In programming, tests (along with 'if' statements) are powerful logical tools. A statement is an element of code that performs an action, like a building block. The if statement allows you to select from different actions depending on the result of a test. Here’s how you write it:

if <test1>:           # if …
    <Do something>
elif <test2>:         # else if …
    <Do something>
else:                 # else …
    <Do something>

Notice the colon at the end of the first line and the indentation (usually four spaces) at the start of the second line, it indicates that those lines are to be executed only if the test result is True. The first two lines are the minimum structure of a loop, but you can also have elif and else parts. Unlike other programming languages, if statements in Python do not have an end statement (e.g. endif or fi). Instead, the end of the if statement is indicated by the end of the indentation.

This will start making sense with a few examples. First read the examples and try to guess what will happen. Then type the examples in a script that you execute. When you type return after the colon, the next line will automatically be indented. Press backspace if you don’t want your text indented (i.e. you want to go to an 'elif' or 'else' part, or end the if statement).

car_color = 'red'
if car_color=='blue':
	print 'The car is blue'
	print 'it’s a cool car'
print 'the end'               # This line is not in the if statement