Control Statements in Python

Intro to Python: Section 4:

What makes computers more than glorified calculators is their ability to use predefined logic to execute a variety of different tasks based on the result of conditional tests.

Control statements are code statements which control the code that gets executed based on a given condition (the conditional statement), which may be true or false. The computer can then execute one set of code if the condition is true, and an entirely different set if the condition is false. You can think of it like a fork in the road, or a lever directing the flow of water through a pipe. This is the basis of algorithm development.

Example

Consider this: a user is registering for your video game website. However, they’re only allowed to register if they’re 13 or older. What might this look like visually?

Conditional Logic Visualized
Conditional Logic Visualized

The user registers for the site by filling out a form. From that, we get their age or calculate it based on their birthday.

We can then use a control statement to see if they’re 13 or older and show them an apology message if they’re too young to register.

If Statements

The simplest type of control statement is an if statement, which checks if a condition is true before doing an action. The format for an if control statement looks like this:

if conditional_statement:
   # do thisCode language: PHP (php)

We’ll look at an example shortly. Note that the control statement is the entire block of code. The conditional statement is a single check that returns true or false.

Comparison Operators

comparison operator compares two values. The greater than/less than comparison operators in Python are the greater/less than signs (sometimes called angle brackets). There’s also an equality comparison, which is two equal signs.

Let’s transform the earlier example into a simplified program. It will ask the user to enter their age as an int. We’ll then check if they’re 13 or older and show them one message. If they’re 12 or younger, a different message.

user_age = int(input("Please type your age. "))
if user_age > 12:
    print("You're old enough to use this site!")
if user_age < 13:
    print("Sorry, you're too young to use this application.")Code language: Python (python)
Terminal
Please type your age. 12
Sorry, you're too young.

The above code stores the user’s age as an int in user_age, it then checks if the value is greater than 12. If they’re older than 12, so 13+, they can use the site. If not, they’re too young.

Recall in the last section we had to parse the string to an int to perform math on it. The same applies to the comparison operators with numbers. If we want to check if a number is greater than another, we must ensure we’re providing the program two numbers – not a String and a number.

In Python, indentations are important. Note that the print statements are indented one step. This means this is a separate block of code executed after the colon. This block of code is usually called the body of the control statement. To break out of the section of code, simply remove the indent. If you want to add additional lines of code to the body of the if statement, ensure each line you want to be executed if the condition is true is indented at the same level.

Now suppose we want to achieve the above, but we want to check if user_age is greater than or equal to thirteen, rather than greater than 12. They’re functionally equivalent, but being able to check if they’re greater than or equal to 13 will make the code more understandable in my opinion.

The greater than or equal to operator is the greater than operator followed by an equal sign (>=). The same applies for less than or equal to (<=). Here’s the same program, but with greater than or equal to.

user_age = int(input("Please type your age."))
if user_age >= 13:
    print("You're old enough to use this site!")

if user_age < 13:
    print("Sorry, you're too young to use this application.")Code language: Python (python)

This new example will produce the same output as the earlier one. But now the second line uses the >= operator.

Finally, let’s print out a special message for anyone who’s 100 using the equality operator (==).

if user_age == 100:
    print("Congratulations on reaching your 100th birthday!")Code language: Python (python)
Terminal
Please type your age. 100
You're old enough to use this site!
Congratulations on reaching your 100th birthday!

In that example, both the second and third control statements were executed, since the user is 18 or older, and is also 100.

The opposite of the equality operator is the not equal operator, which is an exclamation point before an equals sign.

if user_age != 100:
    print("You are not 100 years old.")Code language: Python (python)

If-Else

We can further simplify the above code by introducing an else block to the overall statement. If – Else control statements work just like if statements, except they have a second section defined with the “else” keyword. If the first condition is not true, the else block will be executed instead.

Here’s what that looks like in practice.

user_age = int(input("Please type your age."))
if user_age >= 13:
    print("You're old enough to use this site!")
else:
    print("Sorry, you're too young to use this application.")Code language: Python (python)

This saves us from having to write a long series of similar if statements. We can do it all in one if-else statement.

The else block will always be executed if the first condition is not met. This will be useful in the future, especially if we need to handle an unexpected input.

Else If (elif)

We aren’t limited to just two sections of code, either. We can use else if statements to define an unlimited number of additional conditions to check for if the first isn’t met.

Suppose our program allows 13+ users to register, but we have a voice-chat feature that only 18+ users can use. Now we need to check if the user is under 13, between 13 and 17, and over the age of 18.

One thing to note about else-if blocks – only the first condition met will be executed. If one elif condition is met, it does not continue on to check and see if the remaining conditions are true, too.

So to achieve this, we need to think about the checks we’re performing and what order we place them in. We don’t want a blanket check if they’re greater than 13 first, since that would also include people over 18. We want three separate groups based on age range.

Instead, we should check if they’re 18+ and then 13+. If they’re not 18+ or 13+, the last block will be a generic “else” block that catches the under 13 users.

In many programming languages, else if statements are simply written “else if”. However, Python uses the “elif” keyword, which is slightly shorter and faster to type.

user_age = int(input("Please type your age."))
if user_age >= 18:
    print("You can use this site and use voice chat.")
elif user_age >= 13:
    print("You're old enough to use this site!")
else:
    print("Sorry, you're too young to use this application.")Code language: Python (python)

Write and test the above code if you haven’t been following along. The best way to learn this stuff is to try it out. Ensure it works for all three possibilities.

Logical Operators

Logical operators may determine if a group of conditional statements is true or false. The operators are “and” “or” and “not”. You don’t use a symbol, you just write out the word.

The And Operator

The and operator can check if two or more conditions are true. For a test using only ‘and’ operators to pass, all the conditions must be true for the body to be executed.

Here’s a basic example of using the and operator.

x = 10
y = 5
if (x > y) and (x > 2):
     print("x is greater than y and larger than 2")Code language: Python (python)

Let’s return to the age check program again. This time, we’ll introduce a new variable that shows if the user is a free user or a paid premium user. If they’re a paid premium user, and they’re over the age of 18, we’ll print out a message saying they’re allowed to use voice and video chat. If they’re not a paid user, they can only use voice chat.

Here’s what that code looks like:

user_age = int(input("Please type your age."))
# manually change to "paid" after running the first time to test this
user_group = "free"
if (user_age >= 18) and (user_group=="paid"):
    print("You can use this site. You can use voice chat and "
          "video chat. Thanks for subscribing")
elif (user_age >= 18) and (user_group == "free"):
    print("You can use this site with voice chat, but not "
          "video chat. Please consider subscribing.")
elif user_age >= 13:
    print("You're old enough to use this site!")
else:
    print("Sorry, you're too young to use this application.")Code language: Python (python)

Notice how in line 4 above each condition is in its own group, surrounded by parenthesis. Technically, I don’t need parenthesis here. But as our statements grow more complex, it’s nice to have them grouped.

On lines 5 and 6, I split the string being printed out across two lines. If you’re writing longer strings, it makes sense to do this for easier readability.

Here’s another way we could break users into the same four groups (under 13, 13 to 18, 18+ free, 18+ paid). This time, I’m back tracking to use only if statements.

user_age = int(input("Please type your age."))
# manually change to "paid" after running the first time to test this
user_group = "paid"
if (user_age >= 18) and (user_group=="paid"):
    print("You can use this site. You can use voice chat and "
          "video chat. Thanks for subscribing")

if (user_age >= 18) and (user_group=="free"):
    print("You can use this site with voice chat, but not "
          "video chat. Please consider subscribing.")

if (user_age >= 13) and (user_age < 18):
    print("You're old enough to use this site!")

if user_age < 13:
    print("Sorry, you're too young to use this application.")Code language: Python (python)

Each check occurs individually in the above example. When using this method, it actually doesn’t matter which order the control statements are in. For the user, it would function identically to the earlier examples.

Or Operator

The or operator is like the and operator, as it checks multiple conditions. However, only one condition has to be met for the overall expression to be true.

if condition_a or condition_b:
    print("pass")
else:
    print("fail")Code language: PHP (php)

The above code would print “pass” so long as either of the conditions were true. They could both be true, or one or the other could be true. If they’re both not true, then it would print “fail”. This is useful if you need to execute the same code under a variety of different conditions.

Suppose you’re doing a very basic check to determine if a particular type of fruit can make a good dessert pie. For example, apples, pears, and pumpkins can all make pies. You ask the user to enter the name of the fruit. If it’s one of the fruits you think make a good desert pie, it prints out “… would be good in a pie.”

Let’s do this the longer way, with separate if/elif statements.

fruit = input("Please enter a fruit: ")
if fruit == "apple":
    print("apple would be good in a pie.")
elif fruit == "pear":
    print("pear would be good in a pie")
elif fruit == "pumpkin":
    print("pumpkin would be good in a pie")
else:
    print("I don't think that would be good in a pie.")Code language: Python (python)

The code in the body of each block is very similar, except for the last one. We can combine these to make the code more generic, or reusable. If you ever find yourself writing the same lines of code over and over again, you’re probably not coding efficiently.

Let’s achieve the same result with a single if-else control structure and some ‘or’ operators. We’ll also inject the fruit variable directly into the message printed.

fruit = input("Please enter a fruit: ")

if (fruit == "apple") or (fruit == "pear") or (fruit == "pumpkin"):
    print(fruit, "would be good in a pie.")
else:
    print("I don't think that would be good in a pie.")Code language: Python (python)

Now I’ve saved 4 lines of unnecessary code by combining the output and using the or operator.

There are even better objects available to handle lists of items and compare them. For now, that will suffice.

The Not Operator

The final logical operator is the not operator. It’s functionally equivalent to checking if something is false.

Here’s a simple example:

fruit = input("Please enter a fruit: ")

if not(fruit=="apple"):
    print("You did not type apple.")
else:
    print("You must have typed apple.")Code language: Python (python)

It’s equivalent to this:

fruit = input("Please enter a fruit: ")

if (fruit=="apple"):
    print("You must have typed apple.")
else:
    print("You did not type apple.")Code language: Python (python)

Hopefully, by now you’ve noticed you can achieve the same functional result many ways in Python. This is true of any programming language. With time, you will get better at picking the most efficient option the first time. Remember, you should aim to select the option that seems the most readable and reusable. In the future, we may discuss the performance impact of certain structures.

Nesting Control Statements

In some scenarios, you may want to place control statements within other control statements. To do this, simply place the second control statement within the body of another. The nested or child control statement inside the outer, parent control statement will be executed accordingly.

age = 55
gender = "female"

if age >= 18:
    if gender == "male":
        print("You're an adult male.")
    elif gender == "female":
        print("You're an adult female.")
else:
    print("You're not an adult.")Code language: Python (python)
Terminal
You're an adult female.

Combining Everything

Every operation discussed thus far may be combined in any order you see fit.

age = 29
gender = "male"
user_group = "staff"
user_name = "Robert"

if age < 18:
    print("this won't be executed")
else:
    if not(gender == "female"):
        if (user_group == "staff") and not(user_name == "Sammy"):
            if (user_name == "Robert") or (user_name == "Bob"):
                print("You're an adult male with staff clearance named Robert or Bob.")Code language: Python (python)

The above code would print out the final message at the bottom. Here’s the logic if you need help following:

  • Given: age = 29, gender = male, group = staff, and name = Robert
  • The user is not under the age of 18, else is executed
  • Their gender is not female, it continues to execute the next if statement
  • They are in the user group staff and their name is not Sammy, it continues to next if statement
  • The user’s name is Robert, which is equal to Robert or Bob, so it prints out the last line.

Of course, I wouldn’t expect you to write code that convoluted in the real world. That was just to show all the concepts discussed in this section.

Assignment

Create a program that asks the user to enter two numbers, which are taken as floats. It will then ask if they want to add, subtract, divide, or multiply the first number by the second. Based on what the user enters, perform that operation and print out the result. Use a control structure of some sort.

Here’s what the program output might look like when complete.

Terminal
Welcome to Simple Calculator
Please enter first number. 5
Please enter second number. 10
Would you like to "add" "subtract" "divide" or "multiply" these numbers? add
5 + 10 = 15

Hints

  • If you want to use quotation marks in the print string, encapsulate the entire string with single quotes rather than double quotes. This will allow you to print the quotes. For example, print(‘hello “world”‘) prints the message: hello “world” with quotes.
  • Remember to parse the string input into a float using float(var) where var is the string being converted
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments