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
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
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
Check if the
namevariable contains a value (The
lenfunction 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:
boolean is the simplest data type.
In Python, boolean types use true/false pairs. Let's declare a couple of boolean variables:
theCourseIsExcellent = TruetheAuthorIsHumble = 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:
False value. For instance,
if True: .
2. A variable of a
boolean type. For instance,
if myVar: where
myVar is a
3. An expression that resolves to a boolean value, like in the above example.
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.
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 or equal to
>=Greater than or equal to
Here are some examples using numeric comparison:
2 == 2 # -> True2 == 3 # -> False4 != 4 # -> False4!= 5 # -> True1 < 2 # -> True1 < 1 # -> False1 <= 1 # -> True3 > 4 # -> False5 > 4 # -> True5 >= 4 # -> True
Like any other result, it can be assigned to a variable. For instance:
age=15if 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.
These operators allow you to combine boolean values: either specific boolean values or results of expressions. There are three of them:
The result is true only when all the participating parts are true.
E.g.: the result of
expression1 and expression2will be true only if
expression1is true AND
expression2is also true.
The result is true when at least one of the participating parts is true.
E.g.: the result of
expression1 or expression2will be true if
expression1is true OR
expression2is true. It will also be true if both expressions are true!
It simply inverts the given expression.
The result of
not(expression1)is true when
expression1is false; the result is false when
Here are some examples:
True and True # TrueTrue and False # FalseFalse and False # FalseTrue or False # TrueTrue or True # TrueFalse or False # Falsenot(True) # Falsenot(False) # True
The same rules apply when more than two expressions are chained together:
True and True and True # TrueTrue and True and False # FalseTrue or False or False # TrueFalse 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 # Truenot(False) and True or False # True
As with numeric operators, use parentheses (
()) to change the order:
(True and False) or True # Truenot(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.
myList = [4, 2, 3, 2, 10]myStringList = ["a", "b", "c", "d"]randomString = "The weather is quite beautiful today !"4 in myList # True0 in myList # False0 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:# instructionselif condition2:# instructionselse:# 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 !
Vous n'êtes pas connecté
Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.
Conditions let you execute a block of code only when provided a
booleanvalue, variable, or expression which evaluates to
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.