As you'll be writing more and more sophisticated programs, creating lines of code that always have to execute one line after another in a set sequence will no longer be sufficient. That's where program flow comes in.
In our "Hello, World" program from a previous chapter, we said hello to the world. Wouldn't it be nice if we could be a bit more specific - like saying hello to an actual person? 🙋🏽🙋🏻♂️
Display more specific information if it is available
When starting your program, you may not always know a user's name. So what about something like:
If we know the person's name, display it.
Else keep saying hello to the entire world.
This is what conditions are all about.
How do we get to know the person's name in the first place?
Do you remember print
and len
functions? Here's another one: input
. This one is asking the user of your notebook (you) to enter a character (which can be a sentence) and store it in a variable. Let's see an example:

You have some room to answer the question, and it will be stored in myInput
.
Let's write the code to see if we know our user's name:
Ask our user's name and store his answer in a variable
name
.Check if the
name
variable contains a value (Thelen
function is your friend here).If it does, say hello to our user using his name.
Else, keep saying hello to the world!
Here is the actual code:
name = input("What is your name ?")
if len(name) == 0:
print("Hello World !")
else:
print("Hello", name)
It works! Let's look at how the conditional if statement really works.
Test your conditions with booleans
In Python, to validate a condition, you use a special data type called boolean
. A variable of the boolean
type can hold only two values: True
or False
. A boolean
is the simplest data type.
In Python, boolean types use true/false pairs. Let's declare a couple of boolean variables:
theCourseIsExcellent = True
theAuthorIsHumble = False
Makes sense, doesn't it? 😉
What really matters is that the condition expressed after the if
keyword must resolve to a boolean
. That condition can be expressed as:
1. A True
or False
value. For instance, if True:
.
2. A variable of aboolean
type. For instance, if myVar:
where myVar
is aboolean
type.
3. An expression that resolves to a boolean value, like in the above example.
For instance:
weather="The weather is good"
weather.startswith("The weather") # -> True
startswith
is a method from the String
class that returns True
. If this string starts with the specified prefix, it can, therefore, be used as a condition.
To produce a boolean
, you can also use comparison operators.
Comparison operators
As the name suggests, comparison operators are used to compare two values. There are six of those:
==
Equal to (exactly the same)!=
Not equal to (different in any way)<
Less than<=
Less than or equal to>
Greater than>=
Greater than or equal to
Here are some examples using numeric comparison:
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
Like any other result, it can be assigned to a variable. For instance:
age=15
if age>=21:
# Do something only of age if at least 21
Sometimes, you may want to have more complicated conditions, where the decision depends on the result of a combination of different expressions. This is where you will use logical operators.
Logical operators
These operators allow you to combine boolean values: either specific boolean values or results of expressions. There are three of them:
and
logical AND
The result is true only when all the participating parts are true.
E.g.: the result ofexpression1 and expression2
will be true only ifexpression1
is true ANDexpression2
is also true.or
logical OR
The result is true when at least one of the participating parts is true.
E.g.: the result ofexpression1 or expression2
will be true ifexpression1
is true ORexpression2
is true. It will also be true if both expressions are true!not
logical NOT
It simply inverts the given expression.
The result ofnot(expression1)
is true whenexpression1
is false; the result is false whenexpression1
is true.
Here are some examples:
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
The same rules apply when more than two expressions are chained together:
True and True and True # True
True and True and False # False
True or False or False # True
False or False or False # False
Like with numeric operators, the logical operators respect the priority of operations - the inversion operator not
comes first, then AND operator and
and, finally, OR operator or
. For example:
False or True and True # True
not(False) and True or False # True
As with numeric operators, use parentheses (()
) to change the order:
(True and False) or True # True
not(True and False or not(True)) # True
To reinforce what you've learned, can you calculate the result of following expressions?
not(True) and False and not(True and False) and 4 < 3 or 4 >= 4 or (not(1 == 2) or 3 != 3) and 35 > 34
The general form of a conditional statement in Python is if condition:
where the condition is either a boolean value, a variable of type boolean
, or the result of any expression that produces a boolean value.
The "in" operator
Another important and useful logical operator in Python is the in
operator. It evaluates to true if it finds a variable in a specified sequence (like a list or a string) and false otherwise.
For instance:
myList = [4, 2, 3, 2, 10]
myStringList = ["a", "b", "c", "d"]
randomString = "The weather is quite beautiful today !"
4 in myList # True
0 in myList # False
0 in myStringList # False
"c" in myStringList # True
"e" in myStringList # False
"weather" in randomString # True
"quite" in randomString # True
"rain ?" in randomString # False
In our "Hello, World" example, we have defined an alternative. What if you want to make more complex decisions based on several possible values?
Manage a chain of conditions
We've personalized the welcome message, but what if we want to use more that one first name?
One possibility is to create a chain of conditions. Here is the general form:
if condition1:
# instructions
elif condition2:
# instructions
else:
# instructions
In our "Hello, World" example, the user could send two strings when running the program. We could then send a string containing the concatenation of those two strings:
firstName = input("What is your first name ?")
lastName = input("What is your last name ?")
if len(lastName) > 0 and len(firstName) > 0:
print("Hello", firstName, lastName)
elif len(firstName) > 0:
print("Hello", firstName)
else:
print("Hello World !")
Try it yourself !
Houston... ?
Vous n'êtes pas connecté
Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.
Summary
Conditions let you execute a block of code only when provided a
boolean
value, variable, or expression which evaluates toTrue
.Conditional expressions make use of boolean arithmetic, including comparison and logical operators.
You can evaluate multiple conditions by chaining if/elif/else statements.
In the next chapter, you will see another way to manage the flow of our application: loops.