Control Your Code With Conditional Structures

 

As you work on more and more complex projects, writing a set of lines that run in sequence will not be enough! This is where conditional structures come into play.

In our very first chapters, you saw how to say "Hello, world." Wouldn't it be better to modify this program slightly to be a little more specific and say hello to a particular person?

Print Information if Available

When you start your program, you do not necessarily know the name of the user in advance. How about a program that can:

  • say hello to a particular user, if you know their name...

  • if not, continue to say hello to everyone?

Here is your first condition, which will let you build your first conditional structure.

How can you get a person's name in the first place?

Do you remember functions? Yes, you worked it out, you can do this via a function: the  input  function. This will ask the notebook user (in other words... you!) to enter a string which will then be stored in a variable.

Let's look at an example:

Input function with Jupyter!
Input function with Jupyter!

You have a space to answer the question and your answer will be stored as a string in the   username  variable.

Now design the code that will let you say hello to your user:

  1. Ask the user their name and store their answer in a variable:   name .

  2. Check that the  name  variable definitely contains a value (in case the user doesn't give an answer). The   len  function will help you to perform this task!

  3. If this is the case, say Hello to your user with their name.

  4. Otherwise, keep saying Hello to the world. 

Here is the corresponding code:

name = input( 'What is your name, dear stranger?')
if len(name) > 0:
print("Hello", name, "!")
else:
print("Hello, world!")

It works well! Everything indented below the if is executed if the condition is trueotherwise the program runs everything indented below the else.

Let's take a closer look at how the if structure works in practice.

Use Booleans: The No-Half-Measure Type

In Python, to validate a condition, you use a special type (or object :) ) called boolean. A Boolean variable can only contain two values: True or False. It's actually a pretty simple thing, but oh so useful!

In Python, the boolean can take the values True and False. Now see how to declare booleans in Python:

thisCourseIsGreat = True
itsAuthorIsVeryHumble = False

Easy, right?

To get back to your if conditional structure, I think you'll understand, but it's absolutely necessary that what follows the if keyword results in a boolean. This can be done via:

  • a    True  or   False  value. For example,   if True : .

  • a boolean variable. For example,   if myVariable:  where   myVariable  is a boolean.

  • an expression that results in a boolean value, as in the example above.

For example:

weather = "The weather is great!"
weather.startswith("The weather") # -> True

startswith  is a method of the string class, which returns   True  when the string starts exactly with the string passed as a parameter;  False , if not. For example, you could use this expression to perform an action if a sentence begins with a particular word.

To produce Booleans, you can also use comparison operators.

Comparison Operators

As the name suggests, comparison operators are used to compare two values. There are six main ones:

  • ==  equal to (two values are exactly the same)

  • !=  different from

  • <  less than

  • <=  less than or equal to

  • >  greater than

  • >=  greater than or equal to

Here are some examples with numeric variables:

2 == 2 # -> True
2 == 3 # -> False
4 != 4 # -> False
4!= 5 # -> True
1 < 2 # -> True
1 < 1 # -> False
1 <= 1 # -> True
3 > 4 # -> False
5 > 4 # -> True
5 >= 4 # -> True

The result of these operations can be assigned to a variable:

age=15
if age>=21:
# Do something if age is greater than or equal to 21

Sometimes, you will need more elaborate conditions, where the condition will be the result of combining several expressions. This is where logical operators come in.

Logical Operators

These operators will let you mix several Boolean values: specific Boolean values or expression results. There are three of them:

  • and : the AND operator.
    The final result is true only when all expressions/values are true. For example: the result of  expression1 and expression2  will be True only if   expression1  is true AND expression2  is also true.

  • or : the OR operator.
    The final result is true when at least one of the expressions/values is true. For example: the result of  expression1  or  expression2   will be at True if   expression1  is true OR expression2  is true.

  • not : the NOT operator.
    This simply reverses the result of the given expression. For example, the result of   not(expression)  is true when   expression  is false.

Here are some examples with the results shown as comments:

True and True # True
True and False # False
False and False # False
True or False # True
True or True # True
False or False # False
not(True) # False
not(False) # True

You can also mix more than two expressions/values:

True and True and True # True
True and True and False # False
True or False or False # True
False or False or False # False

As with numeric operations, logical operators respect the priorities of operations: the  not  operator is applied first, then the  and  operator, then the   or  operator. For example:

False or True and True # True
not(False) and True or False # True

You can also use parentheses to change the order:

(True and False) or True # True
not(True and False or not(True)) # True

The general form of a conditional if structure is   if condition:  where the condition can be either a boolean, or a variable of boolean type, or the result of an expression leading to a boolean result.

The  in  Operator

Another useful logical operator in Python is the   in  operator. This returns   True  when a value is found in a sequence (a string or a list);  False , if not.

For example:

myList = [4, 2, 3, 2, 10]
myStringList = ["a", "b", "c", "d"]
myString = "The weather is really good today!"
4 in myList # True
0 in myList # False
0 in myStringList # False
"c" in myStringList # True
"e" in myStringList # False
"weather" in myString # True
"really" in myString # True
"rain?" in myString # False

In your "Hello, world!" example, you have defined only one alternative. What if you have more than one alternative?

Manage a Chain of Conditions

To grant a loan, a bank relies (among other things) on the status of its users' accounts. For example, a naive decision rule might be:

  • If the customer has more than $10,000 in their account, they are automatically approved for their loan.

  • If they have between $100 and $10,000, we need to manually approve their application.

  • Otherwise, the request is denied.

We could use two nested if statements, but Python can link several conditions thanks to the keyword   elif  (contraction of else and if). Here is the general form:

if condition1:
# instructions
elif condition2:
# instructions
else:
# instructions

Here is the code corresponding to the example presented above:

account = input("What is your account balance?")
account = int(account) # transform the answer into an integer
if account >= 10000:
print("Loan granted!")
elif account >= 100 and account < 10000:
print("Loan in process of validation: under study")
else:
print("Loan refused")

Try it for Yourself

Use conditional structures in the following exercise.

You can find the solution right here.

Let's Recap

  • Conditions let you execute a block of code when a Booleanvariable, or expression is true (True).

  • Expressions use Boolean arithmetic, including logical operators and comparison operators.

  • You can apply several conditions with if/elif/else chains.

In the next chapter, you will see another way to control the code via loops.

Post a Comment

Previous Post Next Post