Conditionals and Loops

Conditionals and Loops

This is Part IV of Understanding Programming: A Primer, an exclusive series for EDUKWEST designed to teach you the basics of computer programming.  This series is designed to be a tutorial and you will be the most successful if you work through the tutorial with your text editor open. Key in the code as it appears and try to make it run correctly yourself.  You’ll find that by the end of this series, you’ll be able to develop simple programs and understand the process of computer programming.

In the last article we took a close at variables.  We’re going to be using variables again in this lesson. First, we’ll be using variables to make decisions and execute branching within our program.  Then we’ll use variables to create loops which iterate through a portion of code a number of times.  The two concepts that we cover this month are found in just about every programming language.  So far, the programs we’ve written are all serial– they go through the same steps in the same order each time.  With the addition of conditionals and loops to our programming repertoire, you’re programs will be able to vary their path based on conditions you set.  Sounds like fun, right?

Simple Conditionals

Let’s start by entering some code.  Fire up your development environment and enter the following code using nano or vi:


age = input(“How old are you: “) if age >=21:     print “You are legally able to drink”


When you’ve entered the program in to your text editor, run it three separate times.  The first time, enter an age older than 21.  The next time you run it, enter an age younger than 21.  When you run it one final time, enter 21 exactly.  To make sure the program runs correctly we want to run all the possible scenarios for execution.

You output should appear similar to below:

Figure 1

Figure 1.1:  Program being tested for three different types of user responses

This three-line program is pretty straight-forward here.  What’s new is the if statement.  In this case we’re determining if the value the user entered is greater than or equal to21.  The portion of the if statement written like this:  age>=21 is know as the condition.  Every conditional statement has a condition that is evaluate to be true or false.  If it’s true, the code indented underneath the conditional statement is executed.

Note in the example above, the program responds “You are legally able to drink” only if the user enters a value 21 or greater.  If the code block that runs if the condition is true extends more than one line, please note that each line must have the same level of indentation below the conditional statement.

Python is a bit unusual for modern languages in that it uses indentation to demarcate code blocks.  More traditionally, brackets are used to contain blocks of code.

What Else?

You probably noted that the program we wrote responds only if the conditional is evaluated as true– If it’s evaluate as false the user receives no response.  This is likely confusing for the user.  We’re going to add to the program so that it reacts one way of the condition is evaluate as true and another way if the condition is evaluated as false.


age = input(“How old are you: “) if age >=21:     print “You are legally able to drink” else: print “You are not of drinking age.”


After modifying your program code, run through the three possible scenarios as you did before.  Test a case where the user is under than 21, another where the user is older and a final scenario where the user is exactly 21.  Your output should appear similar to what appears below:

Figure 2

Figure 1.2 Result with the else statement added

As you can tell, the addition of the else statement gave a result if a value under 21 was entered.  When the user enters a value under 21, the condition is evaluated as false and the else statement block is triggered.  Once again, the level of indentation determines what code is in the statement block.

Let’s add just a little bit more code to our program:


age = input(“How old are you: “) if age >=21:     print “You are legally able to drink” else:     print “You are not of drinking age.” if age ==21:     print “Congratulations, here is a free drink.”


Now, if the user says they are exactly 21, the program will print the Congratulatory message.  Note that the comparison operator == was used to denote equality.  If the value in age is exactly 21, the conditional is evaluated as true.

Here are all the comparison operators that you can use with if statements:

== Equal > Greater Than >= Greater Than or Equal < Less Than <= Less Than or Equal != Not Equal

While you can already see the power of conditionals, let’s add a layer of complexity–  What if you wanted to test two values at once?

Compound Conditionals

Let’s pretend that we’re writing software for a college to determine whether or not a specific student made the honor roll.  In our college, to be eligible for honors you must both have a GPA greater than 3.5 and attempt more than 12 hours.

Create a new program in your text editor called honors.py and enter the code below in the file:


gpa = input(“What is your GPA this semester? “ ) hours = input(“How many credit hours did you attempt? “) if gpa > 3.5 and hours > 12:     print “Congratulations, You are on the honor roll” else:     print “Sorry.  You did not make honor role.  Better luck next time.”


Test your program and see what kind of result you get.  Your result should be similar to what appears in the screenshot below:

Figure 3

Figure 1.3:  Two conditions are tested simultaneously.

You’ll notice that in the if statement we joined two conditions by the word and, which, in this case, is acting as an operator.  In this if statement both conditions joined by and must be evaluated as true in order for the whole statement to be true.  The or operator can be used in other circumstances where one condition or the other must be true.  You can join any amount of conditions in a single if statement with and and or operators.

Complex Conditionals with elif

So far the conditionals we’ve created can make decisions in an either/or scenario– either you are eligible to drink, or you’re not.  However, life is more complex than this, which is why if statements can be paired with elif (else-if) statements.  This combination will let you decide from several options as in the program below.

Please key in this program and run it with the Python command to see the result:


age = input(“Enter your age: “) if age < 18:     print “You’re a kid!”     print “Go to school.” elif age < 29:     print “It’s time to be establishing yourself in life”     print “Good luck” elif age < 39:     print “These are good years go focus on career”     print “Get a job” elif age < 49:     print “Time to start thinking about retirement”     print “I hope you are putting money away” elif age < 59:     print “Maintain your health through exercise”     print “Get a trainer” else:     print “You are old”


With apologies to those 59 and older, this program provides feedback based on the age the user enters.  First the user enters their age and this value is assigned to the variable age.  The value entered by the user is then tested in the first part of the if statement.  If the age is less than 18, the program responds with “You’re a kid! Go to School.”

If the first condition turns out to be false, the elif condition is evaluated.  If the age is less than 29 the appropriate advice is dispensed.  If not, the next statement is evaluated.  If none of the conditions associated with the elif statements are found to be true than the unfortunate else statement at the end of the program runs.

Keep in mind that elif statements are only run if all of the previous conditions are found to be false.  Note also the consistent indentation used throughout the else/elif/else is consistent, as is requred in the Python programming language.

While Loops

Loops allow you to run a block of code a number of times.  Each time that block of code is executed is known as an iteration.  Loops are critical to many different types of programs.  Imagine a card game where turns are taken and cards are dealt– all with loops.  If you think about it, you can probably identify loops in many different types of software that you use every day.  The process of waiting for the user to input something, processing that input and then waiting for the user again is often coded in a loop structure.

Let’s code a simple loop:


x = 0 while x < 100:     print x x += 5 print “EOE”


Run the program with the Python command and the result should appear something like this:

Figure 4

Figure 1.4:  The result of a while loop

In the first line of this program we initialize a variable x at the value 0. Next comes our while statement which states that while the value of x is less than 100, the code block indented below the while statement will execute.  In this case the code block prints the value of x to the console and then increases the value x by 5.  Note that the x+=5 notation is shorthand for x=x+5.  += is known as a combined assignment operator.

Here’s another loop example program for you to try.  I saved mine as loop2.py:


band = “” while band != “XXX”: band = raw_input(“Name a band you like of XXX to stop: “) if band != “XXX”: print band, “ROCKS!”


Run the program with the Python command and you should see a result similar to the screenshot below:

Figure 5

When this program initially runs the variable band is set to an empty string.  The value of band is compared to the string “XXX” each time through the loop.  If the loop is anything other than “XXX” the loop iterates again.  If the value is not XXX the name of the band is echoed back to the console.  Once again, notice the indentation in the source code.

Don’t Try This at Home

A common error in programming is an endless loop.  And endless loop is a loop that never ends.  These endless loops can consume more and more computing resources and eventually make the program crash– or worse.  Consider the following code:


x = 1 while x > 0: print x x *= 2


You’ll note that the continuation condition will always be true in this example– The value of x will always be greater than zero.  The value of x very rapidly gets out of hand and, in fact, becomes too big to store in memory.  I ran this in the Koding.com environment and also peeked at the resources being used by my Mac at the time.

Figure 6

Figure 6:  At this point the browser was frozen, but Google Chrome and associated threads took up more than their share of CPU resources.

You can try this example on your own.  I’m not responsible for any damage done.  (Damage won’t be permanent… Have fun!)

See you next time.

Please contact the author at marklassoff@learntoprogram.tv  if you are interested in this and similar lessons for classroom use.

If you are interested in a formal version of this course for yourself or others, LearnToProgram has a special discount for EDUKWEST readers. Programming for Absolute Beginners is the starting point for our Development Club which provides over 30 self-paced courses, and as many live courses as you want to take.  For more information and to access the Edukwest reader discount, visit:

https://learntoprogram.tv/course/ultimate-monthly-bundle/?coupon=EDUKWEST


Picture via Wikipedia

Mark Lassoff is founder of LearnToProgram, Inc., a Connecticut-based company that publishes online courses that teach mobile, web, and game development. Over 100,000 people have learned programming from Mark through online and live classes and free tutorials.