Python if-statements and loops – how to be lazy

We’re moving forward with our training app now. In the previous part Python Programming and Data Structures Part 1 we introduced a training app as an example to work from.

Purpose

The purpose of this post is to introduce the if statement and conditional logic. Why? Because a lot of programming involves deciding between multiple paths.

Goal

By the end of this post you can

  • understand how an if-statement is constructed
  • understand how to use a for loop in simple scenario
  • begin to develop boolean conditions in an if-statement

Prerequisites

You need to have Python installed and be able to start IDLE to follow along. You should be familiar with how to create modules/script and run a Python script, either from the terminal or the GUI window.

A good starting point is this link: How To Install Python On Your Computer

Additionally you should have finished Python data structures part 1 – a look at variables and lists

If you found anything difficult in that part, please let us know! Contact

Python If-statement – make a choice in your application

A Python If-statement gives you more control over a program. With an if-statement, we use the information of a variable to make a choice in your program. For example, if you want to display all exercises when the user responds “Yes,” and show a different message if the user responds “No,” you can use an if-statement.

Let’s see what they look like!

Code Block to Copy

Try the following code in a new script, which we’ll call workout_v2.py:

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

if response == 'Yes':
    print('Here are all the exercises:')
    # more code here ...
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

Python If-statement Analysis

The if-statement in previous listing highlights three branches:

  1. Condition with if: If the user types “Yes,” the code block following the if statement is executed. We call this the first conditional block. The boolean expression (response == ‘Yes’) evaluates to either True or False, depending on what the user typed.
  2. Alternative with elif: If the user types “No,” a different message is displayed.
  3. Invalid response: If the response is something other than “Yes” or “No,” the program shows a message explaining that only those answers are valid.

It’s plain English, yet so important to get it right with Python syntax and indentation. Notice the colon, and the indentation for each block. Otherwise you will get a syntax error when you try to run the program.

Run the code and try typing “Yes,” “No,” and an invalid response (like “Maybe”) to see what happens. You’ll notice that the program becomes more interactive and adapts to the user’s input now. Pretty neat, right?

Python for-loop – loop through exercises with

Next, we wish to complete the code block in the first branch, i.e. when the user type “Yes” – we’ll introduce the concept of loops to let us accomplish that.

for exercise in exercises:
    print(exercise)

When we write for followed by a variable and an in expression, we’re telling the program to loop through each element in a data structure (like a list or tuple) and execute the code in the loop for each individual element.

This will print each exercise on a separate line and the output should look like:

Bench press
Deadlift
Squat
Biceps curl

On each iteration, the print(exercise) works because exercise contain the value from the tuple, one at a time.

In this example:

  1. Starting the loop: for exercise in exercises means that Python starts going through each element in exercises.
  2. Assignment of exercise : For each iteration (loop), exercise becomes the name of one exercise in turn, from ‘Bench press’ to ‘Biceps curl.’
  3. Executing instructions: The code in the loop, print(exercise), is executed each time the loop repeats. So each exercise is printed on its own line.

Insert another statement before the for-loop: print(exercises) and see the result.

How many iterations does the loop run? It depends on the number of elements in the list – the purpose of a for loop is to go through all the elements in the list. The answer is len(exercises), try printing it.

The variable exercises representation should be printed.

Imagine instead if you’d print each exercise on it’s own, that would become cumbersome quickly.

if response == 'Yes':
    print(exercises[0])
    print(exercises[1])
    print(exercises[2])
    print(exercises[3])

Instead, we use the for loop handle the list efficiently, if we had 10 exercises, the for loop wouldn’t change but you’d have to add 6 more rows of print. A for-loop in Python is a powerful tool for repeating instructions multiple times – perfect for lists and other collections.

Using for-loops, we can work efficiently with collections of data and make the program more flexible. Feel free to add your own instructions inside the loop to experiment with how you can handle each element in a list.

if response == 'Yes':
    print('Here are all the exercises:')
    for exercise in exercises:
        print(exercise)
elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

Use the operator “in”

Let’s extend the program by adding a new question asking the user which exercise details to display. To keep things simple, we’ll just print a generic message for each exercise. Add the following after the code above:

selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')

Here, we use in to check if the exercise entered by the user exists in exercises. If it does, we display information about the exercise; otherwise, we inform the user that the exercise isn’t in the schedule.

A note about conditional logic

When we write a if-statement, the result or the branch to enter is evaluated according to a True/False result.

The if-statement anatomy consists of the conditional block and the boolean expression

if True:
    print("This will always be printed")

When we compared the user’s answer of “Yes” or “No”, the result of that comparison would either be True or False internally.

On the other hand, if we’d write

if False:
    print("This will never be printed")

Then we’d never enter that block.

We can create this a boolean expresisons in many number of ways, e.g.

if  5 > 10: # Evaluate to False
    print("5 is greater than 10, is it really?")

if len(some_list) > 100: # Test if the list has more than 100 elements
    print("You have more than 100 elements in the list")

The point is that the conditional block will only be executed if the expression is True. This type of logic becomes important as you want develop the program, it will be necessary as well when you need to limit what is possible in your program. E.g. a scenario would be to never allow more than 5 exercises per session, or you can limit the number of sessions total per week. All these things come into play when you develop the program and it’s only you the designer of the program that decide what is valid in your program.

Finally, it’s also possible to combine multiple checks

if Expression1 or Expression2:
    print("we use the or-condition")

if answer == "Yes" or answer == "yes":
    print("You entered Yes...")

The complete program code

week = 1
schedule = 'Workout A'
exercises = ('Bench press', 'Deadlift', 'Squat', 'Biceps curl')

response = input('Would you like to see all exercises in the training schedule? (Yes/No) ')

if response == 'Yes':
    print('Here are all the exercises:')


elif response == 'No':
    print('Okay, we won’t show any exercises right now.')
else:
    print('Invalid response, please type "Yes" or "No".')

    selected_exercise = input('Which exercise would you like to know more about? ')

if selected_exercise in exercises:
    print(f'You chose {selected_exercise}. This is a fundamental exercise for building strength.')
else:
    print('That exercise is not in the schedule.')

Exercise

  1. Extend the exercises tuple with more exercises.
  2. Improve the exercise details, by creating a different messages for each exercise. You’d need to write an if-statements inside an if-statement.
  3. Extend the if-statement to for the word No, with both uppercase and lowercase “N”. The user should be able to enter either “no” or “No”.
  4. Extend the if-statement in previous exercise to allow more alternatives, e.g. “Nope”, “Nah” or whatever you can think of.
  5. In the next part, we’ll use a dictionary to store descriptions for each exercise in a cleaner way.
  6. Another loop is the while-loop, go to docs.python.org to find out more about it. Use the function len() to determine the condition.

Terminology

Review these terms

  • tuple
  • list
  • if-statement
  • for-loop
  • boolean expression

Summary

In this part, you’ve seen how to use the if-statements in order to handle different scenarios in your program. It allow your program to become more interactive, but also handle things in the code to work according to your plan. Being able to create different options and decision paths in a program is an important part of programming. It makes your programs more dynamic and user-friendly.

In the next part, we’ll dive deeper into working with loops and explore dictionaries.

If you’ve missed the previous post, check it out Python if-statements – beginning the training app

See you in the next section!