Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
Python and Tcl - public course schedule [here]
Private courses on your site - see [here]
Please ask about maintenance training for Perl, PHP, Lua, etc
 
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 answer
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 test.
• 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 or elseif 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 elifs, 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"
  else:
    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 articles
Y103 - Python - Conditionals and Loops
  [4723] Conditional operators in Python - (2016-11-05)
  [4713] Equality (in Python) - (2016-10-30)
  [4545] Method, Class, Module, Package - how to they relate in Python? - (2015-10-17)
  [4541] Setting up and tearing down with the Python with keyword - (2015-10-16)
  [4402] Finding sum, minimum, maximum and average in Python (and Ruby) - (2015-01-19)
  [4323] Learning to program - Loop statements such as while - (2014-11-22)
  [4322] Learning to Program - the conditional statement (if) - (2014-11-21)
  [4210] If elif elif elif - multiway selection in Python - (2013-11-16)
  [4092] Identity in Python - (2013-05-17)
  [3895] Flowchart to program - learning to program with Well House - (2012-10-14)
  [3620] Finding the total, average, minimum and maximum in a program - (2012-02-22)
  [3558] Python or Lua - which should I use / learn? - (2011-12-21)
  [3439] Python for loops - applying a temporary second name to the same object - (2011-09-14)
  [3397] Does a for loop evaluate its end condition once, or on every iteration? - (2011-08-18)
  [3200] How a for loop works Java, Perl and other languages - (2011-03-12)
  [3083] Python - fresh examples from recent courses - (2010-12-11)
  [2899] Groupsave tickets - 3 or 4 train tickets for the price of 2 - (2010-08-02)
  [2778] Learning to program in Python 2 ... and / or in Python 3 - (2010-05-24)
  [1696] Saying NOT in Perl, PHP, Python, Lua ... - (2008-07-04)
  [1661] Equality, sameness and identity - Python - (2008-05-31)
  [1477] Decisions - small ones, or big ones? - (2007-12-18)
  [1201] No switch in Python - (2007-05-23)
  [909] Python is like a narrowboat - (2006-10-30)
  [835] Python - when to use the in operator - (2006-08-16)
  [788] New - Conditional expressions in Python 2.5 - (2006-07-01)
  [668] Python - block insets help with documentation - (2006-04-04)
  [657] The ternary operator in Python - (2006-03-25)
  [353] Wimbledon Neck - (2005-06-20)
  [299] What - no switch or case statement? - (2005-05-03)


Back to
Melksham - placed 2254 out of 2255. What can be done about it?
Previous and next
or
Horse's mouth home
Forward to
Spike solutions and refactoring - a Python example
Some other Articles
Python timing - when to use a list, and when to use a generator
Christmas in June? Melksham hotel bookings and Santa train
Shell, Awk, Perl of Python?
Spike solutions and refactoring - a Python example
Learning 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 Ruby
The five oldest blogs and the horses mouth
Ruby - standard operators are overloaded. Perl - they are not
Ruby - a teaching example showing many of the language features in short but useful program
4759 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2019: 404 The Spa • Melksham, Wiltshire • United Kingdom • SN12 6QL
PH: 01225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3762_Lea ... thon-.html • PAGE BUILT: Sat May 27 16:49:10 2017 • BUILD SYSTEM: WomanWithCat