Learning to program - the if statement. Python.
Statements in a program run sequentially, unless you add specific code to make them do otherwise, with each statement being separated from the next in some way or another.
Should you wish to run a statement in only some circumstances, you can use a conditional statement:
• the word if
(if is available in every language that we teach)
• something which defines the condition under which the next element (statement) is to be run
• the statement that's actually to be run if the condition is true
and there's going to be some extra syntax to tell the language where the various elements start and end
Here's an example from yesterday's "Learning to program in Python" course:
if weeklength < 5: print "OOh Extra Bank Holidaisies"
• the condition being checked is "is the content of the weeklength variable a number less than 5"
• the print statement is only to be performed if the condition check gives a true
And the extra syntax to keep the elements apart?
• there's a space between the word if
and the conditional expression
• there's a colon between the condition itself and the statement that depends on the condition
• there's a new line to indicate the end of the whole conditional statement
In this form of the if
statement in Python, the condition applies only to the statement to its right on the same line, and the following statement in the program will be performed next, whether the condition was false (in which case the conditional statement will be skipped) or true (in which case the conditional statement will NOT be skipped)
If I want to perform different tasks in different conditions, I can write a whole series of if statements, and they will be performed sequentially:
if weeklength 5: print "OOh Extra Bank Holidaisies"
if weeklength == 5: print "Normal week"
if weeklength > 5: print "Back to historical times"
• The use of the double
equals should be noted - it tests whether two values are equal. Python, in common with most language, uses double equals because the single equals sign means somethind different; the single equals is an assignment which says "work out what's on the right and save in to the variable on the left" - very rarely what we want to do as part of an if
• Care should be taken in using the ==
test on numbers which are floating point / real / decimal, as mathematical operations can lead to rounding errors which in some languages and circumstances will lead to your condition being evaluated as false when in theory it should be true.
•As well as < > and == operators, Python and most other languages support <= and >= and an "unequal" operator. Usually that's !=
but in Python you can also use <>
You need to be very careful with your programming if you're always going to want one condition of a series of tests to be tru and the rest false ... it's all too easy to write a series of conditions that should provide a single true result, but in some special case or other provide multiple trues, or no trues at all. So there is a better way:
if weeklength < 5: print "OOh Extra Bank Holidaisies"
elif weeklength == 5: print "Normal week"
else: print "Back to historical times"
• The elif
(could be elsif
in other languages) tests the condition on the second line but only if the first condition was false
. So it ensures against multiple true results, and it also makes the code slighly more efficient as it runs, as the number of tests performed is reduced.
&bull The else
introduced the block of code that's going to be performed only if the test with the if
, and any tests with elif
s, are all false. There's no extra condition attached to it, so it's always going to be performed if none of the other conditions is true - once again, reducing the number of tests that actually need to be run, and at the same time ensuring that one (and only one) of the conditional statements is run.
What if you want to run several
statements if a condition is true? You could perform the test multiple times, but in any good language if you find yourself repeating something, there must be a better way
. Firstly (not shown here), you can add a series of semicolon separated statements after the condition. Or - usually much better - you can provide a whole series of statements, each on its own line, and inset with spaces or tabs to indicate that it forms part of the block
of conditional statements. For example:
if weeklength < 5:
print "OOh Extra Bank Holidaisies"
print "Perhaps it's a Jubilee!"
elif weeklength == 5:
print "Normal week"
print "Why are there no BH's from August to December"
print "Back to historical times"
• The inset can be spaces or tabs (at least one character, and as many as you like, but consistent within the block)
• The block ends when the insetting ends
This block structure is strongly recommended
every time you code and if
statement - at least in your early coding days. For it allows you to come back to the program later on, and very easily add extra instructions within the conditional code without having to re-arrange / refactor. You're learning, even from your early coding, to write code which is robust, easy to follow, and easy to upgrade and maintain later on.
As taught on our Learning to Program in Python course
Source code (and sample output) [here]
We run courses for newcomers to programming AND courses for experienced programmers converting to Python from another language.
Public course schedule [here]
If you have a group of delegates requiring the same course at the same time, we can also run a private course at our training centre
or a private course at your offices
(written 2012-06-12, updated 2012-06-16)
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articlesY103 - Python - Conditionals and Loops 
Conditional operators in Python - (2016-11-05) 
Equality (in Python) - (2016-10-30) 
Method, Class, Module, Package - how to they relate in Python? - (2015-10-17) 
Setting up and tearing down with the Python with keyword - (2015-10-16) 
Finding sum, minimum, maximum and average in Python (and Ruby) - (2015-01-19) 
Learning to program - Loop statements such as while - (2014-11-22) 
Learning to Program - the conditional statement (if) - (2014-11-21) 
If elif elif elif - multiway selection in Python - (2013-11-16) 
Identity in Python - (2013-05-17) 
Flowchart to program - learning to program with Well House - (2012-10-14) 
Finding the total, average, minimum and maximum in a program - (2012-02-22) 
Python or Lua - which should I use / learn? - (2011-12-21) 
Python for loops - applying a temporary second name to the same object - (2011-09-14) 
Does a for loop evaluate its end condition once, or on every iteration? - (2011-08-18) 
How a for loop works Java, Perl and other languages - (2011-03-12) 
Python - fresh examples from recent courses - (2010-12-11) 
Groupsave tickets - 3 or 4 train tickets for the price of 2 - (2010-08-02) 
Learning to program in Python 2 ... and / or in Python 3 - (2010-05-24) 
Saying NOT in Perl, PHP, Python, Lua ... - (2008-07-04) 
Equality, sameness and identity - Python - (2008-05-31) 
Decisions - small ones, or big ones? - (2007-12-18) 
No switch in Python - (2007-05-23) 
Python is like a narrowboat - (2006-10-30) 
Python - when to use the in operator - (2006-08-16) 
New - Conditional expressions in Python 2.5 - (2006-07-01) 
Python - block insets help with documentation - (2006-04-04) 
The ternary operator in Python - (2006-03-25) 
Wimbledon Neck - (2005-06-20) 
What - no switch or case statement? - (2005-05-03)
Some other Articles
Python timing - when to use a list, and when to use a generatorChristmas in June? Melksham hotel bookings and Santa train Shell, Awk, Perl of Python?Spike solutions and refactoring - a Python exampleLearning to program - the if statement. Python.Melksham - placed 2254 out of 2255. What can be done about it?Why you should use objects even for short data manipulation programs in RubyThe five oldest blogs and the horses mouthRuby - standard operators are overloaded. Perl - they are notRuby - a teaching example showing many of the language features in short but useful program