Chp-5: Conditionals#

Chapter Objectives

By the end of this chapter, the student should be able to:

  • Explain the purpose and role of conditional statements.

  • Define boolean values.

  • Apply conversion functions between different data types and boolean values.

  • Demonstrate how to use if, if-else, and if-elif-else statements.

  • Demonstrate how nested if statements handle various conditions.

  • Apply boolean operators.

  • Perform comparison operators in conditional expressions.

  • Use try and except to handle errors effectively.

  • Solve real-world problems, such as determining letter grades in a course.

Motivation#

In our daily lives, our actions often depend on various conditions. For instance:

  1. If the temperature is above 60, I will go hiking; otherwise, I will stay at home.

  2. If I work less than 40 hours per week, my hourly rate is 25 dollars. For each additional hour, I earn 40 dollars.

  3. Depending on my financial situation:

    • If I have more than 5,000 dollars, I will go on a cruise.

    • If I have between 3,000 and 5,000 dollars, I will go to Florida.

    • If I have less than 3,000 dollars, I will spend time in my city.

  4. In my math course, the letter grade is determined by a grading scale. For instance, getting 76 results in a C+.

The central question in this chapter is how to write a program that performs different tasks under various conditions. This allows us to answer questions such as whether to go outside or stay at home based on the temperature, how much to earn depending on weekly working hours, where to travel, or what grade a student will receive according to the grading scale.

Conditionals#

Conditionals are the statements that allow you to execute different blocks of code based on whether certain conditions that are True or False.

We have seen the following data types so far:

  • int: Integers

  • float: Floats

  • str: Strings

  • bool: Boolean

Since conditionals are the main subject of this chapter, booleans will be the commonly used data type.
We have already encountered boolean values when working with:

  • in and not in operators for strings return boolean values.

  • startswith(), isdigit(), and isalpha() string methods also return boolean values.

Booleans#

The values of booleans are limited to two: True and False.

  • They are keywords in Python and cannot be used as variable names.

  • boolean True(False) and string 'True' ('False') are different.

x = True
y = False
z = 'True'
t = 'False'
print(type(x))   # x is a boolean 
<class 'bool'>
print(type(y))   # y is a boolean 
<class 'bool'>
print(type(z))   # z is a string
<class 'str'>
print(type(t))   # t is a string
<class 'str'>

Conversions#

  • The built-in bool() function is used to convert integers, floats, and strings to boolean values.

  • The built-in int(), float(), and str() functions are used to convert boolean values to integers, floats, and strings respectively.

bool <–> int#

The integer values of boolean True and False are 1 and 0 respectively.

  • bool –> int

    • int(True) = 1

    • int(False) = 0

The boolean value of all integers except 0 is True, whereas the boolean value of 0 is False.

  • int –> bool

    • bool( any integer other than 0 ) = True

    • bool(0) = False

print(int(True))      # int value of True is 1 
1
print(int(False))     # int value of False is 0
0
print(bool(6))        # bool value of 6 is True
True
print(bool(-101))     # bool value of -101 is True
True
print(bool(23.567))   # bool value of 23.567 is True
True
print(bool(0))        # bool value of 0 is False
False
  • You can perform algebraic operations with boolean values True and False.

  • In such operations, True takes on the integer value 1, and False takes on the integer value 0.

print(True+1)   # True+1=1+1=2
2
print(False*5)  # False*5=0*5=0
0

bool <–> float#

The float values of boolean True and False are 1.0 and 0.0 respectively.

  • bool –> float

    • float(True) = 1.0

    • float(False) = 0.0

The boolean value of all floats except 0.0 is True, whereas the boolean value of 0.0 is False.

  • float –> bool

    • bool( any float other than 0.0 ) = True

    • bool(0.0) = False

print(float(True))      # float value of True is 1.0
1.0
print(float(False))     # float value of False is 0.0
0.0
print(bool(23.567))     # bool value of 23.567 is True
True
print(bool(0.0))        # bool value of 0.0 is False
False
print(True+4.6+True+False+10+True+False)  # 1+4.6+1+0+10+1+0
17.6

bool <–> str#

The string values of boolean True and False are ‘True’ and ‘False’ respectively.

  • bool –> str

    • str(True) = ‘True’

    • str(False) = ‘False’

The boolean value of all strings except '' (empty string) is True, whereas the boolean value of '' (empty string) is False.

  • str –> bool

    • bool( any string other than empty string ) = True

    • bool( empty string ) = False

      • empty string = ''

print(str(True))      # str value of True is 'True'
True
print(str(False))     # str value of False is 'False'
False
print(bool('HELLO'))   # bool value of 'HELLO' is True
True
print(bool(''))        # bool value of '' = empty string is False
False

Boolean Expressions (Conditions)#

Boolean expressions are those that evaluate to either True or False.

Comparison operators#

The table below presents the meanings of the most commonly used operators in boolean expressions. Warning: Since = is used for assignment, == is used for comparison.

Operator

Meaning

==

equal (only value not type)

!=

not equal (only value not type)

<

less than

<=

less than or equal to

>

greater than

>=

greater than or equal to

is

equal (value and type)

is not

not equal to (value and type)

Comparison of strings:

  • Inequality operators follow the dictionary order.

  • Uppercase letters are considered before lowercase letters.

  • Digits are considered before uppercase letters.

  • The order is as follows: Digits < Uppercase letters < Lowercase letters.

  • The is keyword checks for identity.

    • Objects compared with is have the same id() numbers, indicating they are stored in the same location in memory.

  • The == operator checks for equality.

    • It compares whether the values are the same or not.

    • For example, 4 and 4.0 are considered equal mathematically, even though their data types are different.

  • When you use is with strings, numbers, or booleans, a syntax error occurs.

    • The error suggests using == or != for these types.

print(5==5)  # 5 is equal to 5 is True
True
print(5==7)  # 5 is equal to 7 is False
False
print(3==3.0) # The mathematical value of 3 and 3.0 are equal is True
True
print(5!=5)  # 5 is not equal to 5 is False
False
print(5!=7)  # 5 is not equal to 7 is True
True
print(5<7)   # 5 is less than 7 is True
True
print(10>15)  # 10 is greater than 15 is False
False
print('k'=='t')  # 'k' is equal to 't' is False
False
print('k'=='k')  # 'k' is equal to 'k' is True
True
print('K'=='k')  # 'k' is equal to 'K' is False (case sensitive).
False
print('k' < 't')  # 'k' comes before  't' in dictionary order is True
True
print('z' < 't')  # 'z' comes before  't' in dictionary order is False
False
print('money' < 'table')  # 'money' comes before 'table' in dictionary order is True
True
print('Z' < 'a')  # capital letters come before lower case letters in dictionary order 
True
print('3' < 'A')  # digits come before  letters in dictionary order 
True
# SyntaxWarning: Use == instead
print( 'k' is 'K')
# SyntaxWarning: Use == instead
print( 2 is 3)

if statement#

The if statement executes a block of code based on a condition, typically a boolean expression, which evaluates to either True or False.

  • If the condition is True, a block of code will be executed.

  • If the condition is False, the block of code will not be executed and will be skipped.

  • The structure of an if statement is as follows:

if condition:
            
   BLOCK CODE
            

In the structure above:

  • if is a keyword.

  • condition is a boolean expression, which is either True or False.

  • : comes right after the condition and means this line will be followed by another code.

  • BLOCK CODE is a group of code with the same indentation level that will be executed if the condition is True.

There are two cases:

  1. The condition is True:
    if True:
                
       BLOCK CODE   BLOCK CODE will be executed.
                

  2. The condition is False:
    if False:
                
       BLOCK CODE   BLOCK CODE will be skipped.
                

In the code below:

  • condition is True because 75 > 65, so the block code will be executed.

  • BLOCK CODE consists of two lines of code, and they will be executed.

grade = 75

if grade > 65:        
    print('You passed.')
    print('Congrats!')
You passed.
Congrats!

In the code below:

  • condition is False because 55>65 is False, so the block code will not be executed.

  • BLOCK CDDE consists of two lines of code, and they will be skipped.

  • There is no output for this code.

grade = 55

if grade > 65:        
    print('You passed.')
    print('Congrats!')

In the code below:

  • condition is False because 55>65 is False, so the block code will not be executed.

  • BLOCK CDDE consists of two lines of code and they will be skipped.

  • The last print statement is not part of the BLOCK CODE. After skipping the BLOCK CODE, this last print statement will be executed.

grade = 55

if grade > 65:        
    print('You passed.')
    print('Congrats!')
print('Bye')
Bye
  • As a condition, numbers, strings, and boolean values can be directly used.

  • Python will automatically convert them into boolean values.

# condition is always True
# Hello will always be printed.

if True:
    print('Hello')
Hello
# condition is always False
# print statement will be skipped. 
# no output

if False:
    print('Hello')
# condition is always True because bool(5)=True
# Hello will always be printed

if 5:
    print('Hello')
Hello
# condition is always False because bool(0)=False
# no output

if 0:
    print('Hello')
# condition is always True because bool('NY')=True
# Hello will always be printed.

if 'NY':
    print('Hello')
Hello
# condition is always False because bool('')=False
# no output

if '':
    print('Hello')
  • If the block code of an if statement consists of only one line, it can be written right after the colon (:), keeping the entire if statement in a single line.

grade = 55
if grade > 35: print('You passed.')  
You passed.

if-else statement#

This is for two-statement situations.

  • If the condition is True, the block code of the if statement will be executed as before.

  • If the condition is False, the block code of the else statement will be executed.

  • The else keyword is used for the second part.

  • The else part does not have a condition part.

  • Warning: The indentation level of if and else must be the same.

if condition:
                    
   BLOCK CODE of if 
                    
else:
                    
   BLOCK CODE of else
                    

  • The cases are as follows:

  1. The condition is True:

if True:
                    
   BLOCK CODE of if    BLOCK CODE of if statement will be executed.
                    
else:
                    
   BLOCK CODE of else   BLOCK CODE of else statement will be skipped.
                    

  1. The condition is False:

if False:
                    
   BLOCK CODE of if    BLOCK CODE of if statement will be skipped.
                    
else:
                    
   BLOCK CODE of else   BLOCK CODE of else statement will be executed.
                    

  • In the code below:

    • condition is True because 75 > 65 is True, so the block code of the if statement will be executed.

    • The block code of the else statement will be skipped.

    • The output comes from the print statements of the if part.

grade = 75

if grade > 65:        
    print('You passed.')
    print('Congrats!')
else:
    print('You failed.')
    print('I am sorry.')
You passed.
Congrats!
  • In the code below:

    • condition is False because 55>65 is False, so the block code of the else statement will be executed.

    • The block code of the if statement will be skipped.

    • The output comes from the print staements of the else part.

grade = 55

if grade > 65:        
    print('You passed.')
    print('Congrats!')
else:
    print('You failed.')
    print('I am sorry.')
You failed.
I am sorry.
  • If the block code of an if or else statement consists of only one line, it can be written right after the colon (:), keeping the entire if or else statement in a single line.

grade = 55

if grade > 35: print('You passed.')  
else: print('You failed.')
You passed.

if-elif-else statement#

This is for three-case situations.

  • If there are more cases, then more elif parts can be added.

  • If the condition of the if statement is True, the block code of the if statement will be executed.

  • If the condition of the if statement is False and the condition of the elif statement is True, the block code of the elif statement will be executed.

  • If the conditions of the if and elif statements are False, then the block code of the else statement will be executed.

  • The elif keyword is used for the second part.

  • elif has a condition part.

  • Warning: The indentation level of if, elif, and else must be the same.

  • The structure of an if-elif-else statement is as follows:

if condition of if:         
                     
   BLOCK CODE of  if 
                     
elif condition of ELIF:
                     
   BLOCK CODE of elif
                     
else:
                     
   BLOCK CODE of else
                     

  • The cases are as follows:

  1. The condition of if statement is True:

if True:
                     
   BLOCK CODE of  if    BLOCK CODE of if statement will be executed.
                     
elif condition of elif:
                     
   BLOCK CODE of elif   BLOCK CODE of elif statement will be skipped.
                     
else:
                     
   BLOCK CODE of else   BLOCK CODE of else statement will be skipped.
                     

  1. The condition of if statement is False and condition of elif statement is True:

if False:
                    
   BLOCK CODE of  if   BLOCK CODE of if statement will be skipped.
                    
elif True:
                    
   BLOCK CODE of elif   BLOCK CODE of elif statement will be executed.
                    
else:
                    
   BLOCK CODE of else   BLOCK CODE of else statement will be skipped.
                    

  1. The conditions of if and elif statements are both False:

if False:
                    
   BLOCK CODE of  if   BLOCK CODE of if statement will be skipped.
                    
elif False:
                    
   BLOCK CODE of elif   BLOCK CODE of elif statement will be skipped.
                    
else:
                    
   BLOCK CODE of else   BLOCK CODE of else statement will be executed.
                    

  • In the code below:

    • condition of the if statement is True because 75>65 is True, so the block code of the if statement will be executed.

    • The block code of the elif and else statements will be skipped.

    • The output comes from the print statements of the if part.

grade = 75

if grade > 65:        
    print('You passed.')
    print('Congrats!')
elif grade > 55:
    print('You could not pass!')
    print('You can take the test one more time.')
else:
    print('You failed.')
    print('I am sorry.')
You passed.
Congrats!
  • In the code below:

    • condition of the if statement is False because 60>65 is False

    • condition of the elif statement is True because 60>55 is True

    • So the block code of the elif statement will be executed.

    • The block code of the if and else statements will be skipped.

    • The output comes from the print statements of the elif part.

grade = 60

if grade > 65:        
    print('You passed.')
    print('Congrats!')
elif grade > 55:
    print('You could not pass!')
    print('You can take the test one more time.')
else:
    print('You failed.')
    print('I am sorry.')
You could not pass!
You can take the test one more time.
  • In the code below:

    • condition of the if statement is False because 40>65 is False

    • condition of the elif statement is False because 40>55 is False

    • So the block code of the else statement will be executed.

    • The block code of the if and elif statements will be skipped.

    • The output comes from the print statements of the else part.

grade = 40

if grade > 65:        
    print('You passed.')
    print('Congrats!')
elif grade > 55:
    print('You could not pass!')
    print('You can take the test one more time.')
else:
    print('You failed.')
    print('I am sorry.')
You failed.
I am sorry.

Nested if statements#

It is possible to have an if, if-else, or if-elif-else statement within a block code for if, elif, or else.

age = 10
weight = 45

if age > 5:                     # True: execute the block code within this `if` statement, which includes an `if-else` statement.
    if weight>50:               # False: skipped
        print('A')
    else:                       
        print('B')              # executed
B
age = 10
weight = 55

if age > 5:                     # True: execute the block code within this `if` statement which consists of an `if-else` statement
    if weight>50:               # True: executed
        print('A')
    else:                       
        print('B')              # skipped
A
age = 3
weight = 45

if age > 5:                     # False: skip the block code within this `if` statement which consists of an `if-else` statement
    if weight>50:               
        print('A')
    else:                       
        print('B')              
else:                           # this 'else' statement corresponds to the first 'if' statement.
    print('C')                  # executed
C

Boolean Operators#

Boolean operators include and, or, and not.

  • and, and or are used to construct more complex boolean expressions.

  • not is the negation operator.

  • &,| can be used instead of and, or respectively.

These operators, also called logical operators, work as follows:

  • The and operator returns True if both operands are True; otherwise, it returns False.

  • The or operator returns True if at least one of the operands is True; it returns False only if both operands are False.

  • The ‘not’ operator returns the opposite boolean value of the operand. If the operand is True, ‘not’ returns False, and vice versa.

Value

Operator

Value

=

Result

True

and

True

=

True

True

and

False

=

False

False

and

True

=

False

False

and

False

=

False

Value

Operator

Value

=

Result

True

or

True

=

True

True

or

False

=

True

False

or

True

=

True

False

or

False

=

False

  • not True = False

  • not False = True

print(True and False)
False
print(True & False)   # and
False
print(True or False)
True
print(True | False)  # or
True
print(not True)
False
print(not False)
True
# True and True = True
print( (3 > 1) & (10 > 8) )
True
# False or True = True
print( (7 == 8) | (10 > 8) )
True
# not True = False
print( not ('arm'<'kite'))
False
# not False = True
print( not ( 'a' in 'Apple' ))  # a i snot in Apple
True

Example-1

  • If the (weather is nice) or (I have $5), then I will buy an ice cream.

    • If either of the conditions is True, I will buy an ice cream.

    • If both of the conditions are False, I will not buy an ice cream.

  • So, we have the following scenarios based on weather conditions and the amount of money available:

    • (weather is nice) = True or (I have $5) = True ——> buy an ice cream

    • (weather is nice) = False or (I have $5) = True ——> buy an ice cream

    • (weather is nice) = True or (I have $5) = False ——> buy an ice cream

    • (weather is nice) = False or (I have $5) = False ——> do NOT buy an ice cream

Example-2

  • If the (weather is nice) and (I have $5), then I will buy an ice cream.

    • If both of the condtions are True, I will buy an ice cream.

    • If either of the conditions is False, then I will not buy an ice cream.

  • So we have the following cases depending on the weather conditions and money amount:

    • (weather is nice) = True and (I have $5) = True ——> buy an ice cream

    • (weather is nice) = False and (I have $5) = True ——> do NOT buy an ice cream

    • (weather is nice) = True and (I have $5) = False ——> do NOT buy an ice cream

    • (weather is nice) = False and (I have $5) = False ——> do NOT buy an ice cream

temperature = 100
money = 3

print(f'Temperature is {temperature}.')
print(f'I have ${money}.')

if temperature > 75 and money > 5:    # True and False = False
  print('Go outside!')                # skipped
else:
  print('Stay at home!')              # executed
Temperature is 100.
I have $3.
Stay at home!
temperature = 100
money = 10

print(f'Temperature is {temperature}.')
print(f'I have ${money}.')

if temperature > 75 and money > 5:    # True and True = True
  print('Go outside!')                # executed
else:
  print('Stay at home!')              # skipped
Temperature is 100.
I have $10.
Go outside!

try and except#

It is similar to an if-else statement. If there is an error in the code, the entire program will be terminated. To prevent termination in the presence of errors, a try-except statement is often used.

  • This kind of situation is very common, especially when a user enters input that is not appropriate.

    • entering “one” instead of digit “1”

    • making typos like “5s” instead of “5”

  • If you try to convert such inputs to a number, an error will occur, and the entire program may be terminated.

  • To handle such situations gracefully, you can use a try-except statement

  • try-except works as follows:

    • If there is no error in the block code of the try part, this block code will be executed.

    • If there is an error in the block code of the try part, the block code of the except part will be executed.

  • The structure of a try-except statement is as follows:

try:
                      
   BLOCK CODE of try  
                      
except:
                      
   BLOCK CODE of except
                      

  • The cases are as follows:

  1. BLOCK CODE of try has no error:

try:
                      
   BLOCK CODE of try     BLOCK CODE of try will be executed.
                      
except:
                      
   BLOCK CODE of except   BLOCK CODE of except will be skipped.
                      

  1. BLOCK CODE of try has an error:

try:
                      
   BLOCK CODE of try     BLOCK CODE of try will be skipped.
                      
except:
                      
   BLOCK CODE of except   BLOCK CODE of except will be executed.
                      

  • In the following code, there is no error in the try block, so the try block will be executed.

num =  '5'
try:
    x = int(num)**2                                 # no error: '5' can be converted to an int
    print(f'Square of {num} is {x}')                # executed
except:
    print('Warning: Please enter an integer.')      # skipped
Square of 5 is 25
  • In the following code, there is an error in the try block, so the except block will be executed.

num =  '5s'
try:
    x = int(num)**2                                 # error: '5s' can not be converted to an int
    print(f'Square of {num} is {x}')                # skipped
except:
    print('Warning: Please enter an integer.')      # executed
Warning: Please enter an integer.

Remark

  • You must include the except part along with some code when using the try statement.

  • If you don’t intend to perform any specific actions in the except part, you can use the pass keyword to prevent an error.

num =  '5s'
try:
    x = int(num)**2                                 # error: '5s' can not be converted to an int
    print(f'Square of {num} is {x}')                # skipped
except:
    pass                                            # does not do anything

No output

Examples#

Even or Odd#

Ask for an integer from the user and check whether it is even or odd.

  • Print your result using f-strings in the form of “The given number is even/odd.”

Solution

number = int( input('Enter an integer:') )

if number%2 == 0:                            # for even numbers, the remainder is zero, so this condition is True.
  print(f'{number} is an even number')
else:
  print(f'{number} is an odd number')

Greater than ten#

Ask the user for an integer and check whether it is greater than 10 or not.

  • Print the result using f-strings in the form: “The given number is greater/not greater than 10.”

Solution

number = int(input('Enter an integer:'))

if number>10 :                              # this condition is True if the number is greater than 10.
  print(f'{number} is greater than 10')
else:
  print(f'{number} is not greater than 10.')

Same names#

Ask for two names from the user using two input() functions and check whether these names are the same.

  • It should not be case-sensitive, meaning that “Tom” and “TOM” are considered the same name.

  • Print the result using f-strings in the form of “name1 and name2 are the same/not the same.”

  • Print the names exactly as given by the user.

Solution

name1 = input('Please enter the first  name:')
name2 = input('Please enter the second name:')

if name1.lower() == name2.lower():             # compare lower case versions to make it not case sensitive.
  print(f'{name1} and {name2} are same.')
else:
  print(f'{name1} and {name2} are not same.')

Letter Grades#

Write a program that asks the user to enter a percent grade.

  • Display the corresponding letter grade according to the following chart.

Letter Grade

Grade Range

A

80 - 100

B

60 - 79

C

40 - 59

D

20 - 39

F

0 - 19

Solution

grade = float(  input( 'Enter your percent grade:' )  )

if 80 <= grade <= 100:
    print('Your letter grade is A')
elif 60 <= grade :
    print('Your letter grade is B')
elif 40 <= grade :
    print('Your letter grade is C')
elif 20 <= grade :
    print('Your letter grade is D')
elif 0 <= grade :
    print('Your letter grade is F')
else:
    print(f'{grade} is not a percent grade')

Piecewise Defined Function#

The piecewise-defined function \(f(n)\) is given as follows:

\[\begin{split} f(n) = \begin{cases} 4-2n & n < -2 \\ 5 & -2 \le n \le7\\ 1-n & n>7 \\ \end{cases} \end{split}\]
  • Write a program that asks the user to enter an integer.

  • If the integer entered is n then display f(n).

  • Hint:

    • If n is less than -2 then f(n)=4-2n

    • If n is greater than or equal to -2 and less than or equal to 7 then f(n)=5

    • If n is greater than 7 then f(n)=1-n

  • Example:

    • \(f(-4) = 4-2(-4)=12\) since \(-4<-2\)

    • \(f(1) = 5\) since \(-2\le1\le7\)

    • \(f(10) = 1-10=-9\) since \(10>7\)

Solution

n = int(   input('Please enter a number:')    )

if n < -2:
    print(f'f({n})={4-2*n}')
elif -2 <= n <= 7:
    print(f'f({n})=5')
else:
    print(f'f({n})={1-n}')

Secret Number Game#

Choose a random integer between 1 and 10 as the secret number.

  • Ask a number from the user to guess it.

  • If the user’s guess is correct, display You win!

  • If the user’s guess is incorrect, display Incorrect. Try again!!

  • Cheating Part:

    • If the user’s guess is 99999, display You win!

  • Use try and except to avoid errors if the user enters non-numeric values.

  • Warn the user if there is an error by displaying a message.

Solution

import random
secret_number = random.randint(1,10)

try:
  player = int(input('Guess the number: '))

  if player == secret_number:
    print('You win!')
  elif player == 99999:       # cheating part
    print('You win!')
  else:
    print('Incorrect. Try Again!')
      
except:
  print('Please enter a valid numeric value!')