Conditional Statements
Boolean values
The CPU executes the instructions of a program as a sequence in the order written by the programmer. Execution of a Python program starts with the first line of code and ends with the last line of code; each line is executed. In many programs, the programmer wants to control the flow, that is, to change the order of execution according to some specific logic. This happens in our real lives. For example, when we are offered a dish, ideally, we would eat only if we feel hungry (assuming we never eat if we're full!). Therefore, some of our actions depend if a specific condition is true. Another example is that we go to work everyday if there is no holiday and we are not on leave. Thus, sometimes our conditions are complex and consist of multiple subparts. Many programming languages do allow us to specify conditions based on truth values. If a condition is true something happens, and if a condition is false something else happens.
To write conditional statements, we must first understand how truth is specified in Python. In Python, we have a simple type for specifying truth, which we call the Boolean type. A variable can have a Boolean type. Some expressions evaluate to Boolean values. There are two Boolean values: True and False (both keywords). We can assign a Boolean value to a variable, and we can also construct Boolean expressions.
x = True
y = 1 > 2
A binary relational operator (<
, >
, <=
, >=
, ==
, !=
) specifies a relation between two objects and results in a Boolean value. As shown in the example above, the value of x
is True,
but the value of y
is False
because 1 is not greater than 2.
We can also specify compound relations. In this case, a condition may consist of two or more sub-conditions.
z = a > b and a > c
In the program above, we're using the and
operator, a logical operator. There are three of them: and
, or
, and not
. We can use the logical operators to connect multiple conditions and create a single final Boolean value. The value of z
in the statement above depends on the numeric values of a
, b
, and c
.
We can also use membership operators: in
and not in
. These are used with sequence types. For example, we can use in
to check if a particular element is in a list.
x = 'a' in 'hello'
y = 1 in [1,2,3,4]
The value of x
is False
, but y
is True
. Having these operators helps in establishing conditional statements, which we will study next.
Conditional statements
A conditional statement has several forms. One simple conditional statement is the if
-statement. One can specify for the computer to check if a specific condition is true and do something accordingly. For example, the following program asks the user to guess the value of x
, a nonnegative integer less than 10. If the user answers correctly, the program cheers the user.
x = 3
guess = int(input('Guess the value of x: '))
if guess == x:
print('You made it!')
As you can see, we should use the if
keyword followed by a condition that evaluates to a Boolean value (either True
or False
) followed by a colon. If the condition is true, we want to tell the computer to execute some statements. These statements are below the if
-statement with a mandatory indentation. Note that the print
statement is only executed if guess
is equal to x
. The double equal sign indicates equality instead of the single equal sign, which means assignment.
We want to make our program more interesting. We want to say something to the user when the user's guess is not correct. In that case, Python's if
-statement can be completed with an else
-statement.
x = 3
guess = int(input('Guess the value of x: '))
if guess == x:
print('You made it 😄')
else:
print('Try harder 🧐')
If guess
is equal to x
, the first print
statement is executed. Otherwise, the second print
statement is executed. It's impossible that both statements are executed since else
is the opposite of if
.
This program can be even more interesting. We want to hint to the user that even though the guess was not correct, the value of guess
was very close to x
. So, if the difference between guess
and x
is less than two, the user is very close. Otherwise, the user must try harder. In this case, we have three cases, so we need something more than if
and else
. We can use an elif
to accomplish this task.
x = 3
guess = int(input('Guess the value of x: '))
if guess == x:
print('You made it 😄')
elif abs(guess - x) <= 2:
print("You're very close 😅")
else:
print('Try harder 🧐')
In this program, the computer first checks if guess == x
. If this was true, both elif
and else
will not be executed as if they did not exist. If guess
is not equal to x
, the computer first checks if abs(guess - x) <= 2
is true. If it was true, it will execute the print
statement beneath it and will forget about else
. If both if
and elif
were not true, the program will execute the else
statement for sure.
Another version of the program adds one more elif
to tell the user that the guessed value is too far from the actual value. We assume if the difference between guess
and x
is 8 or more, then the user is way too far away.
x = 3
guess = int(input('Guess the value of x: '))
if guess == x:
print('You made it 😄')
elif abs(guess - x) <= 2:
print("You're very close 😅")
elif abs(guess - x) >= 8:
print("You're very far away 🙃")
else:
print('Try harder 🧐')
Finally, we will add a little bit of randomness to this program. We won't fix the value of x
to 3. Instead, we'd like to pick a random integer in a specific range and assign it to x
. Luckily, Python has a library for that, which is called random
. We can use one of the functions defined in random
to pick an integer value in a specific range of our choice.
import random
x = random.randint(0,10)
guess = int(input('Guess the value of x: '))
if guess == x:
print('You made it 😄')
elif abs(guess - x) <= 2:
print("You're very close 😅")
elif abs(guess - x) >= 8:
print("You're very far away 🙃")
else:
print('Try harder 🧐')
This program first picks a random integer in the range [0,10] and assign it to x
. Then, it continues as before and checks the user's guess. Try it on your computer and have fun.
String and List Comparisons
We can compare two strings using relational operators. This is because characters are represented as numbers in memory. Each character that we can include in a string is stored as a number. For example, 'a' is 97, 'b' is 98, and so on. Since small letters and capital letters are different in Python, their numeric values are also different. For example, 'A' is 65. To know the numeric representation of characters we can use a built-in function called ord(x)
, where x
is a single-character string. The value returned from ord(x)
is the numeric representation of the character in x
. The numeric representation is based on the ASCII table, which designates an integer to represent a character. Even emojis are represented as numeric values because they are made of several ASCII characters.
Given that strings are actually numbers in memory, Python allows us to compare them. Try the following if
-statements to know how they are compared.
if 'a' > 'A':
print('a is greater than A')
if 'z' < 'x':
print('z is less than x')
What if we want to compare strings with multiple characters? To compare a string T
with a string S
, Python compares the first n = min(len(T),len(S))
characters of T
with those of S
starting from the first character on the left. If the compared characters are equal, then T
and S
are equal. Otherwise, the relationship between S
and T
is based on the first character of the n
characters that are different in T
and S
. When two strings have the same n
characters, the one with more characters becomes the bigger.
T = 'abc'
S = 'az'
x = T < S
y = '1200' > '160'
In the program above, the value of x
is True
because T
and S
differ in the second character where b
is less than z
. Therefore, T
is less than S
. Similarly, the value of y
is False
because the two strings 1200
and 160
differ in 2
and 6
where 6 > 2
.
Lists are not different than strings in relational comparisons. The following program shows this.
T = [1,2,6]
S = [1,2]
x = T > S
y = [1,6] < [1,2]
The value of x
is True
here because [1,2,6]
has more elements than [1,2]
although the first two elements of T
are equal to the elements of S
. The value of y
is False
because 6 > 2
.
Using Boolean-valued methods
There are methods that return Boolean values. Strings have such methods, which can be very useful. Suppose that we would like to write a program to decide if a given string has a numeric value (either integer or a float value). This can be done using some String methods.
First, as usual, we'd receive the string from the user. Then, we can simply check if the string contains only digits by using a method called S.isdigit()
, which returns True
only if all the characters in the string S
are digits.
S = input()
if S.isdigit():
print(S,'is a number')
else:
print(S,'is not a number')
If you try this program with the string "10"
, it will print 10 is a number
, but what if we enter 10.5
? It will print 10.5 is not a number
. The reason is that 10.5
has the decimal point in it, which is not a digit. To go around this problem, we can use another method S.replace(x,y)
, where S
, x
, and y
are all strings. This method replaces every occurrence of x
with y
in the string S
and returns the resulting string as a new value.
S = input()
if S.replace('.','').isdigit() and s.count('.') < 2:
print(S,'is a number')
else:
print(S,'is not a number')
This time, with an input of 10.5
, we will get 10.5 is a number
. We replaced every occurrence of '.'
with an empty string ''
. The resulting string only includes the digits so we can decide if S
is a numeric value. The program also prevents strings with more than one dot to be reported as numeric. This is done with the condition s.count('.') < 2
, which checks if the number of dots in the string is less than 2.
Other useful Boolean-valued methods for strings:
str.endswith(x)
doesstr
end withx
?str.isalnum()
doesstr
contain only English alphabet characters or numeric characters?str.isalpha()
doesstr
contain only English alphabet characters?str.isdigit()
isstr
a digit?str.islower()
isstr
lower case?str.isupper()
isstr
upper case?str.isspace()
doesstr
contain only spaces?str.startswith(x)
doesstr
start withx
?