SPSS tutorials website header logo SPSS TUTORIALS FULL COURSE BASICS ANOVA REGRESSION FACTOR

Conditions and Loops in Python

Common parts of any computer language are conditions, loops and functions. In Python, these have fairly similar structures as illustrated by the figure below.

Python For Loop Structure

a function, loop or condition is terminated by a colon;
one or more indented lines indicate that they are subjected to the condition or loop or part of some function;
an outdented line indicates that some loop, condition or function has ended.

Loops, conditions and functions are often nested as indicated by their indentation levels. The syntax below shows a commented example.

*PYTHON CONDITION IN FOR LOOP EXAMPLE.

begin program python3.
for ind in range(10): # start of loop
    print('What I know about {},'.format(ind)) # subjected to loop
    if(ind % 2 == 0): # start of condition
        print('is that it\'s an even number.') # subjected to loop and condition
    else: # end previous condition, start new condition
        print('is that it\'s an odd number.') # subjected to loop and condition
print('That will do.') # end condition, end loop
end program.

Let's now take a closer look at how loops and conditions are structured in Python.

Python “for” Loop

In Python, we mostly use for loops in which we iterate over all elements of an iterable object. As it's perfectly straightforward, a single example may do.

*PYTHON "FOR" LOOP EXAMPLE.

begin program python3.
countries = ['Netherlands','Germany','France','Belgium','Slovakia','Bulgaria','Spain']
for country in countries:
    print(country)
print("That's all.")
end program.

Note that the indentation indicates where the loop ends: “That's it.” is printed just once because it's not indented.

Python “while” Loop

A second type of Python loop is the “while” loop. It'll simply keep iterating as long as some condition is met. Make sure that at some point the condition won't be met anymore or Python will keep looping forever -or until you somehow disrupt it anyway, perhaps with Windows’ Task Manager.

We rarely use “while” loops in practice but I'll give an example below anyway: we'll randomly sample zeroes and ones while the number of ones in our sample is smaller than 10. If we endlessly repeat this experiment, the sample sizes will follow a negative binomial distribution.

*ADD RANDOM ZEROES AND ONES TO SAMPLE AS LONG AS THERE'S FEWER THAN 10 ONES IN THE SAMPLE.

begin program python3.
import random
sample = []
while sum(sample) < 10:
    sample.append(random.randint(0,1))
print(sample)
end program.

*NOTE: SECOND/THIRD/... ATTEMPTS TYPICALLY RESULT IN SHORTER/LONGER LISTS.

Python “if” Statement

Conditional processing in Python is done with if statements and they work very similarly to for and while. Let's first run a simple example.

*SIMPLE IF STATEMENT.

begin program python3.
countries = ['Netherlands','Germany','France','Belgium','Slovakia','Bulgaria','Spain']
for country in countries:
    if 'm' in country:
        print('%s contains the letter "m".'%country)
end program.

Python “if-else” Statement

Our previous example did something if some condition was met. If the condition wasn't met, nothing happened. Sometimes that's just what we need. In other cases, however, we may want something to happen if a condition is not met. We can do so by using else as shown below.

*IF AND ELSE EXAMPLE.

begin program python3.
countries = ['Netherlands','Poland','Germany','Portugal','France','Belgium','Slovakia','Bulgaria','Spain']
for country in countries:
    if country.startswith("S"):
        print('%s starts with an "S".'%country)
    else:
        print('%s doesn\'t start with an "S".'%country)
end program.

Python “if-elif-else” Statement

Our last example took care of two options: a condition is met or it is not met. We can add more options with elif, short for “else if”. This means that a condition is met and none of the previous conditions in our if structure has been met.

Like so, an if structure may contain (at the same indentation level):

Example

*IF, ELIF AND ELSE EXAMPLE.

begin program python3.
countries = ['Netherlands','Poland','Germany','Portugal','France','Belgium','Slovakia','Bulgaria','Spain']
for country in countries:
    if country.startswith("S"):
        print('%s starts with an "S".'%country)
    elif country.startswith("P"):
        print('%s starts with a "P".'%country)
    else:
        print('%s doesn\'t start with a "P" or an "S".'%country)
end program.

Tell us what you think!

*Required field. Your comment will show up after approval from a moderator.