A Boolean is a type of data that is either True or False and cannot be any other value.
A Boolean expression is an expression that evaluates to a Boolean value, either True or False. We can combine Booleans with logical operators to make Boolean expressions.
What do these Boolean expressions evaluate to?
not True
True and False
False or False
True and not False
(Click for answers)
False
False
False
True
Complicated Boolean expressions might have several logical operators. Just like the order of operations for arithmetic expressions, there is an order of precedence that logical operators obey. The order of precedence is as follows:
Parentheses
Not
And
Or
We can use Booleans in conditional statements. A conditional statement allows us to execute code only if a certain condition is True. A basic conditional statement is comprised of only an if clause. This is what the syntax looks like:
if <condition>:
<body>
The <body> code is only evaluated if the <condition> is True. The body can be as many lines of code as it needs to be, but each line must be indented to tell Python that it is part of the conditional body.
For this exercise, set the variable my_condition so that the message is printed.
For this exercise, write an if statement that adds 1 to the variable visitor_count if the variable is_student is NOT true.
Let's say the first condition wasn't true. What if we want to check another one? This is what the elif clause is for. This is what the syntax looks like:
if <condition-1>:
<body-1>
elif <condition-2>:
<body-2>
elif stands for "else if", meaning that its condition will only be checked if none of the previous conditions were true. Therefore, in a sequence of if-elif clauses, at most one of the bodies of the clauses will be evaluated, if any.
Whenever using elif, we always need an if clause first followed by as many elif clauses as we would like.
The last type of clause that can be used in a conditional statement is an else clause. Else clauses don't have a boolean condition, and act as a catch-all for any remaining cases if all previous conditions evaluate to False. Here's the basic syntax for an if statement with an else clause:
if <condition-1>:
<body-1>
else:
<body-2>
If an else clause is included in an if statement, it is always the last clause and there is at most one.
For this exercise, write a conditional statement that checks the variable is_allowed .
If is_allowed is True, set a variable called message to "Welcome!"
Otherwise, set message to "Access denied"
For this exercise, we've defined two variables, eight_characters and contains_number to check the strength of a password. Write a conditional statement that sets a variable called password_strength depending on the following criteria:
If both variables are True, set password_strength to "Strong"
If only one of the variables is True, set password_strength to "Medium"
Otherwise, set password_strength to "Weak"