Conditional Statement
Contents
Conditional Statement#
There comes situations in real life when we need to make some decisions and based on these decisions, we decide what should we do next. Similar situations arise in programming also where we need to make some decisions and based on these decisions we will execute the next block of code, or not.
Decision-making statements in programming languages decide the direction of the flow of program execution. These decision-making statements include:
functions
conditional statements, and
loops
Control flow refers to the order in which individual statements,
instructions, or function calls are executed or evaluated.
We start to learn control flow by diving into the conditional statements,
i.e., if-else
conditions.
The conditional statement checks to see if a statement is True
or False
.
So, executing a conditional statement outputs a Boolean.
Here is a simple example:
a = 62
b = 71
print(a == b)
False
Note
“=” is the assignment operator.
“==” is a comparison operator.
Comparison operators are used to form conditions. Python supports the usual logical conditions from mathematics:
Symbol |
Meaning |
Example |
Result |
---|---|---|---|
|
Equal to |
|
|
|
Not equal to |
|
|
|
Greater than |
|
|
|
Less than |
|
|
|
Greater than or equal to |
|
|
|
Less than or equal to |
|
|
1. if-else
statement#
if statement is one of the most common conditional statements.
It is used to decide whether a line of code or a block of codes will
be executed if the condition is true, i.e., True
.
Otherwise, the codes immediately following it will not be executed.
if a == 71:
print('a equals to 71')
if a == 62:
print('a equals to 62')
a equals to 62
Use in
or not in
with a list to test if a list contains a specific element.
states = ['Florida', 'New York', 'California']
if 'Florida' in states:
print('Florida is in the list.')
if 'Texas' not in states:
print('Texas is not in the list.')
Florida is in the list.
Texas is not in the list.
Code Block Definition
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Missing indentation will raise an exception (IndentationError
).
By convention, indentation is four white spaces.
The colon after the if statement is required.
Most code blocks, such as loops and functions start by a colon.
Most IDEs will automatically add indentation after colon is typed.
# the following code will raise an Indentation Error
if a == 62:
print('a equals to 62')
File "C:\Users\chjch\AppData\Local\Temp\ipykernel_3388\4165433191.py", line 3
print('a equals to 62')
^
IndentationError: expected an indented block
We now understand that if statement can determine whether to run certain statements.
But what if we want to do something else if the condition is false (False
).
Here comes the else statement.
x = '+'
if x == '+':
print('x is a plus sign')
else:
print('x is not a plus sign')
x is a plus sign
The Else-If statement (elif
) is used when the else condition might not suffice.
This is used mostly in those cases when you have to justify more than two results.
x = '-'
if x == '+':
print('x is a plus sign')
elif x == "-":
print('x is a minus sign')
else:
print('x is neither a plus nor a minus sign')
x is a minus sign
2. Comparing two numbers#
num_1 = 784533
num_2 = 763092
if num_1 > num_2:
print(str(num_1) + " is greater than " + str(num_2))
elif num_1 < num_2:
print(str(num_1) + " is smaller than " + str(num_2))
else:
print(str(num_1) + " is equal to " + str(num_2))
784533 is greater than 763092
Tip
The input
statement allows user to dynamically insert inputs.
Then, use the inserted values to carry out the rest of statements.
The type of values inserted by input
is string (str
).
num_1 = int(input("Enter first number: "))
num_2 = int(input("Enter second number: "))
if num_1 > num_2:
print(str(num_1) + " is greater than " + str(num_2))
elif num_1 < num_2:
print(str(num_1) + " is smaller than " + str(num_2))
else:
print(str(num_1) + " is equal to " + str(num_2))
Warning
String comparison always compare the first character according to the ASCII table. This can results in conterintuitive results. See example below.
'45' > '245'
True
3. Compound condition#
In many situations, a decision is not made only by a single condition. For example, a number is an even number if it is an integer and can be completely divided by 2. To write a more complicated condition, we can use compound Boolean expressions which are combinations of multiple conditions, i.e., variables and values that produce a Boolean value.
To write compound conditions we need to use logical operators (or boolean operators).
Assume a = True
and b = False
, then
Symbol |
Meaning |
Example |
Result |
---|---|---|---|
|
Both expressions are True |
|
|
|
At least one of the expressions is True |
|
|
|
The expression is not True |
|
|
True or False # Returns True if one of the statements is true
True
True and False # Returns True if both statements are true
False
Tip
You can directly use True
or False
in your code or assign them to a variable. You can then update the variable’s value later.
not True # Reverse the result
False
Now let’s see how we can extend the example of comparing two numbers by adding compound conditions.
num_1 = int(input("Enter first number: "))
if num_1 > 10:
print(str(num_1) + " is greater than 10.")
elif num_1 > 5 and num_1 <= 10:
print(str(num_1) + " is smaller or equal to 10 but greater than 5.")
elif num_1 > 0 and num_1 <= 5:
print(str(num_1) + " is smaller or equal to 5 but greater than 0.")
else:
print(str(num_1) + " is negative.")