Python if-statements and loops – how to be lazy

Welcome to the beginning parts of Learn Python In A Normal Way. In this series we’re working on our own Training App. The series focuses on how to get up and running with logical thinking and programming with Python, and it should suit the beginner since doing assignments is what makes you learn quicker.

In this part we’re moving forward with our training app and learn Python if-statements, for-loop introduction and more!

Make sure you’ve read the previous part Python data structures part 1 – a look at variables and lists

Purpose

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

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 must 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 Us

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?

A note about conditional logic

When we write an if-statement, the code block or the branch to enter is evaluated according to a boolean expression. It’s the same as asking a Yes/No question, but in the computer world we call this 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. Why?

Here are more examples of boolean expressions, where we use the comparion operator greater than >. The first evaluates whether 5 is greater than 10 (False obviously). The second checks if the length of the variable some_list exceeds 100.

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 purpose is to only execute part of the code when the boolean expression is True. In the above example it’s simply just one print statement. This is something we will see more of and learn about as we move along.

This type of logic becomes important as you want develop the program, also when when you want to put constraints in your program.

Imagine a scenario to never allow more than 5 exercises per workout day, or where you can limit the number of sessions total per week. All these things require some kind of conditional logic to exist in your program. Therefore as you gain experience and develop the program, it’s only you as the designer of the program that can decide what is valid in your program or not.

Finally, let’s look at how to combine multiple expressions, to check several conditions at the same time.

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

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

The second example becomes handy when you want to let a user be more flexible, you will allow “Yes” and “yes” as an answer to a question, you’ll try to implement this in your program too with the exercises.

Python for-loop – loop through exercises with

Now let’s get back to our program, and look at the first branch i.e. the boolean expression where the user type “Yes” – we’ll introduce the concept of loops now. Remember, the program should display all exercises, according to the question presented to the user

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

if response == "Yes":
  print("Here are all the exercises:")
  for exercise in exercises:
    print(exercise)

Notice the construct: keyword for followed by a variable, followed by keyword in followed by a variable (a list or tuple).

for variable1 in variable2

This tells 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. For our program, it will print each exercise on a separate line, and the output should look like the following. Run the program and confirm you see the same.

Bench press
Deadlift
Squat
Biceps curl

On each iteration print(exercise) works because exercise is bound or assigned the value from the tuple, one value 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 inside the for-loop block, right above print(exercises) and see the result. Don’t forget to add same indentation.

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 after the loop.

print("The length of exercises is ", len(exercises))

Alternatively, imagine if you had a really long list, you’d have to print each exercise on its own line. Something that would become cumbersome quickly.

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

Now you see the purpose of the the for loop to handle the list (or tuple) efficiently. So, if we had 10 exercises, the for loop wouldn’t change at all. However, you’d have to add 6 more rows of print, which one is better?

Remember 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”

Python has a neat operator we can use called in. Let’s demonstrate how to use it in our program. Extend the program by adding a new question asking the user which exercise details to display. In programming terms, we want to search the tuple exercises for a value, namely the exercise the user type into the program dialogue.

As a result, 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.

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.')

Exercises

  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!