Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2023 (and 2024 ...) - we are now fully retired from IT training.
We have made many, many friends over 25 years of teaching about Python, Tcl, Perl, PHP, Lua, Java, C and C++ - and MySQL, Linux and Solaris/SunOS too. Our training notes are now very much out of date, but due to upward compatability most of our examples remain operational and even relevant ad you are welcome to make us if them "as seen" and at your own risk.

Lisa and I (Graham) now live in what was our training centre in Melksham - happy to meet with former delegates here - but do check ahead before coming round. We are far from inactive - rather, enjoying the times that we are retired but still healthy enough in mind and body to be active!

I am also active in many other area and still look after a lot of web sites - you can find an index ((here))

Well House Consultants
You are on the site of Well House Consultants who provide Open Source Training Courses and business hotel accommodation. You are welcome to browse and use our resources subject to our copyright statement and to add in links from your pages to ours.
Other subject areas - resources
Java Resources
Well House Manor Resources
Perl Resources
Python Resources
PHP Resources
Object Orientation and General topics
MySQL Resources
Linux / LAMP / Tomcat Resources
Well House Consultants Resources
Extras Resources
C and C++ Resources
Ruby Resources
Tcl/Tk Resources
Web and Intranet Resources
Python module Y103
Conditionals and Loops
Exercises, examples and other material relating to training module Y103. This topic is presented on public courses Learning to program in Python, Python Programming

How to write code in Python that's only run if a certain condition is met, and how to repeat a piece of code more than once.

Related technical and longer articles
the while and else structure

Articles and tips on this subjectupdated
4723Conditional operators in Python
Python does NOT support the ? and : condiitonal operator. Instead, the and and or keywords are lazy. Look at this example which seeks out the longest line in a file and tells you how long it is:   fh = open("ac_20160516.xyz")   loli = 0   while True:     l ...
2016-11-06
 
4713Equality (in Python)
"Equality" ... lovely subject. We're all equal in the eyes of many laws these days - man or workman, able bodied or not, young or old, left or right handed, any colour or religion. But just because we're equal doesn't mean we're the same. In Python, the == operator returns True if the two parameters ...
2016-10-30
 
4545Method, Class, Module, Package - how to they relate in Python?
A file containing a number of python methods and classes is known as a module. In the simplest of cases, it mighy just contain one class. A directory containing a number of python modules is known as a package. In the simplest of cases, it may just contain one module. Here's a sample program that loads ...
2015-10-17
 
4541Setting up and tearing down with the Python with keyword
Python's with operator lets you set up and tear down an object for use in a bock of code - typically useful for a file handle / resource accessor. Here's an example of it in use:   with day() as today:     print ("Today it is " + today) It's set up using the __enter__ ...
2015-10-16
 
4402Finding sum, minimum, maximum and average in Python (and Ruby)
A fresh example (in Python) from today's "learning to program in" course ... finding the number, sum, minimum and maximum of a series of numbers typed in. See [here]. We start off with zero for the count and sum to date, but we do not initialise the minimum or the maximum as we don't know what they ...
2015-01-19
 
4323Learning to program - Loop statements such as while
If your program always ran each statement just once (indeed skipping over statements which were in blocks in false conditions) it would run very quickly and would have little use. You couldn't (for example) run a program which went through a whole series of results from a database query and displayed ...
2014-11-22
 
4322Learning to Program - the conditional statement (if)
Every language has some sort of conditional statement. That's a way of looking at some sort of setting or status in the program and performing some sort of action based on that setting or status. such statements take the form ...   if {some sort of condition is true} then {run a group of ...
2014-11-22
(longer)
3200How a for loop works Java, Perl and other languages
Java, Perl, PHP, Ruby, C, C++, Tcl and many other languages support a "for" loop construct. When your program enters the top of the loop, it performs the first statement in the brackets ... in this Perl example, that's to initialise the $now variable to 1. It then evaluates the expression given as ...
2014-02-02
 
4210If elif elif elif - multiway selection in Python
Most languages have "if / else if / else if / else " type constructs for selecting conditional code, although the format / keyword varies between languages, in the case if Python, the intermediate keyword is elif. In all cases with this construct, you can think of it as like peeling an onion - taking ...
2013-11-19
 
4092Identity in Python
There's a differece between "the same", "equal" and "identical". I can have two identical 5p coins, but they're not the same coin. And I can have two coins which are not identical, but are equal in value. And when you're checking for equality in a program, you should know which you're looking at. Take ...
2013-05-18
 
3895Flowchart to program - learning to program with Well House
Drawing a flowchart is how many people understand a process; it's something that's been used in schools and textbooks for many generations, and it provides a graphic representation of choices and actions that most people find easy to follow. For newcomers to programming, such as on my Learning to program ...
2012-10-20
 
3620Finding the total, average, minimum and maximum in a program
There are a number of programming techniques which the experienced coder takes for granted, but which aren't necessarily intuitive for the newcomer. Call them "design techniques" or "design patterns" that need to be learned, if you want some fashionable buzzwords. • To produce the sum of a stream ...
2012-10-08
 
3762Learning 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 ...
2012-06-16
(longer)
3397Does a for loop evaluate its end condition once, or on every iteration?
All the languages that we teach have a for loop or the equivalent, which is a clean way of repeating a block of code with a rising or falling index number. It's used in many circumstances - for example in iterating through the months of the year (for m goes from 1 to 12) of in stepping through all ...
2012-04-15
 
3558Python or Lua - which should I use / learn?
"Should I learn and use Python or Lua" - a question to me. The questioner was perceptive, knowing that he shouldn't try to learn lots of languages at the same time, and that he should always limit the "basket" of languages used within his applications - in fact, he was wondering if he could select just ...
2011-12-24
(longer)
3439Python for loops - applying a temporary second name to the same object
If you write a for loop in Python to go through each element of a list, you assign an extra (temporary) name to each member of the list while within the loop. So than any changes made to the named variable will also be changes to the object in the original list. However, that's overshaddowed / overtaken ...
2011-09-14
 
3083Python - fresh examples from recent courses
During courses, I write a lot of examples in front of delegates so that the get to see both a program to perform a certain task and how that solution was reached - after all, they'll be expected to modify and write programs after the course, and just showing them the final result would only be telling ...
2010-12-13
(longer)
2899Groupsave tickets - 3 or 4 train tickets for the price of 2
First Great Western offer "Groupsave" tickets where 3 or 4 adults can travel for the price of two on most off peak, book at time of travel, services. And children can go along at a pound each. But there's no "Groupsave 5", so if there are five of you, you'll need to buy a Groupsave 4 plus an extra ...
2010-08-02
 
2778Learning to program in Python 2 ... and / or in Python 3
Yesterday - "Learning to Program in Python" - and I'm now teaching the day so that it's both Python 2 and Python 3 compatible. But it's really an intro day, and we'll vary how we go for the following 3 days of the course, majoring in an appropriate direction for our group - that's a luxury we have when ...
2010-05-25
 
657The ternary operator in Python
The ? : operator that you may have come across in Perl, PHP, C and Java - known as the ternary or conditional operator - is ABSENT from Python. "But it's so useful" I hear you cry. Ah yes, but isn't this elegant: val = float(raw_input("Age: ")) status = ("working","retired")[val>65] print "You should ...
2010-01-03
 
909Python is like a narrowboat
I'm giving a Python course today, to a team of seasoned programmers, and of course I'm coming up with a few things that are different to the languages they know. So far, we've had ... * No switch statement * No ++ operator * blocks indicated via insets * else clauses on while loops Of course, this ...
2009-01-01
 
1696Saying NOT in Perl, PHP, Python, Lua ...
"Isn't there one standard way to say NOT?" asked one of my delegates on today's course - and it's an excellent question. But the answer to a question about a negative subject is itself in the negative - no, there isn't just a single way! In fact .. I can think of no fewer that 12 ways! • 1. ! ...
2008-07-05
 
1661Equality, sameness and identity - Python
Is the number 7.0 the same as the number 7.00000? A trick question, because it depends on how you look at it. It has the same value, but it is not identical. And if eachof them is held in computer memory, there's no chance at all that they're both the same thing - i.e. held in the same memory location ...
2008-06-01
 
1477Decisions - small ones, or big ones?
When you're traveling, you'll sometimes come to a point at which you make a decision - to go one way or to go another. Sometimes the decision is a small one - for example, if I'm driving through Marlborough there's a choice of the town centre or the road around the back; whichever I take, they come ...
2007-12-19
 
1201No switch in Python
Question There's no switch statement in Python. Why not? (Poor) Answer Because there's no need .. you can use a series of if and elif statments. And we can't do it in Python because there isn't a label syntax that would be needed for case. Better Answer If you come to write some code where a switch ...
2007-05-23
 
835Python - when to use the in operator
Python's in construct, when used with an if statement, lets you loop through all the members of a collection (such as a list or a tuple) and see if there's a member in the list that's equal to the pattern - thus val = 17 if val in [1,4,5,7,12,14,17,20,34]: print "yes" will print out "Yes". For looking ...
2006-08-16
 
788New - Conditional expressions in Python 2.5
Python has always been described as a "tight" language in that new syntaxes are only added with a great deal of thought, and then only if they provide a significant benefit without diluting the crispness of the language. There have been long discussions in the Python world about adding in a conditional ...
2006-07-04
 
299What - no switch or case statement?
Both Perl and Python lack a switch and case type contruct that you'll find in almost any other programming language. Why's this? Switch and case, where provided, give a multiway branch capability but - quite frankly - I've always found them to be messy constructs in all the various languages that I've ...
2006-06-05
 
Examples from our training material
b1.py   if - elif - else conditional
bp   Exchange Rate Conversion answer
cally.py   Days and months exercise - answer using methods
combo.py   Combining conditions with and and or
eqt   Comparions
george   if / elif / elif - how it works
goal.py   when is a number "false"?
groupsave   Groupsave ticket calculator
if1.py   an if statement in python
if2.py   if with a block
if3.py   Nested blocks
if4.py   if, elif and else
isy   is or == in Python
ken   single and multiple statement blocks / conditionals
lenny   First Loop
python_switch_case   Alternative to switch, case and default
shand.py   Shorthand operators
shin   with as and in
sintea   Singapore Teapot - exercise answer
sintea2   Singapore Teapot - exercise answer (2)
swans.py   Swan family - Python
tab2.py   loop controls - break and else
table.py   a loop in python
three.py   if statments - various ways of writing them
Pictures
Learning to program in Python
Background information
Some modules are available for download as a sample of our material or under an Open Training Notes License for free download from [here].
Topics covered in this module
Conditional statement - if.
blocks in Python.
else and elif.
Conditions, and what is truth.
The while loop.
break and continue; else clauses.
Shorthand operators.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule page.

Well House Consultants specialise in training courses in Ruby, Lua, Python, Perl, PHP, and MySQL. We run Private Courses throughout the UK (and beyond for longer courses), and Public Courses at our training centre in Melksham, Wiltshire, England. It's surprisingly cost effective to come on our public courses - even if you live in a different country or continent to us.

We have a technical library of over 700 books on the subjects on which we teach. These books are available for reference at our training centre.


You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2024: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/resources/Y103.html • PAGE BUILT: Sun Oct 11 14:50:09 2020 • BUILD SYSTEM: JelliaJamb