4 ConditionalStatements

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Conditional Statements

Sokratis Sofianopoulos
What are conditional statements
• In computer science, conditional statements are
features of a programming language, which perform
different computations or actions depending on
whether a programmer-specified Boolean condition
evaluates to true or false
• The control flow of the program changes based on
some condition

2
Arithmetic operators used as Boolean operators

• The statements introduced in this chapter will involve tests or conditions


• More syntax for conditions will be introduced later, but for now consider simple
arithmetic comparisons that directly translate from math into Python
• Less than: <
• Greater than: >
• Less than or equal: <=
• Greater than or equal: >=
• Equals: ==
• Not equal:!=

3
Assignment vs. Boolean evaluation

•x=2
• print(x == 2) # prints out True
• print(x == 3) # prints out False
• print(x < 3) # prints out True

4
Simple if Statements
• General Syntax
if condition :
indentedStatementBlock
• If the condition is true, then do the indented statements
• If the condition is not true, then skip the indented statements
• Example (using input from the user):
age = int(input("How old are you? ")) #Python doesn't evaluate the data type, you have to
explicitly convert to int
if age < 17:
print("You must be older than 17 to vote.")
print(“Program flow continues here…")

5
if-else Statements
• general Python if-else syntax
if condition :
indentedStatementBlockForTrueCondition
else:
indentedStatementBlockForFalseCondition
• There are two indented blocks:
• The first is right after the if heading and is executed when the condition in the if
heading is true
• The second is right after the else statement, and is only executed when the original
condition is false
• In an if-else statement exactly one of two possible indented blocks is executed

6
if-else Statement example

age = int(input("How old are you? "))


if age < 17:
print("You must be older than 17 to vote.")
else:
print("You are free to vote.")
print("Program flow continues here…")

7
if-elif Statements
• General syntax
if condition1 :
indentedStatementBlockForTrueCondition1
elif condition2 :
indentedStatementBlockForFirstTrueCondition2
elif condition3 :
indentedStatementBlockForFirstTrueCondition3
else:
indentedStatementBlockForEachConditionFalse
• Exactly one of the indented blocks is executed → the one corresponding to the 1st True condition
• If all conditions are False, it is the block after the final else line

8
Exercise

• Write a program called sign.py that asks the user for an integer number
• Print out which category the number is in:
• 'positive'
• 'negative'
• 'zero'

9
Boolean operators

• In Python we can combine multiple Boolean statements using the


Boolean operators:
and, or and not
• For "and" and "or" we can also use & (bitwise and) and | (bitwise
or) respectively
• The difference is that with and/or the condition is evaluated lazily
while with the bitwise operators it is not

10
The not operator

• The not operator when used before a Boolean expression it


inverts that expression
• Example:
• print(not False)
• x=1
print(not x==1)

11
Boolean operators and/or example

day = "Friday"
date = 13
if day == "Friday" and date == 13:
print("Today is Friday the 13th! Good luck.")
if (day == "Tuesday" or day == "Friday") and date==13:
print(" Today is the 13th and it is either Friday or Tuesday! Good luck.")

How do you think Python handles case comparison with strings?

12
Chaining comparison operators

• Comparison operators can be chained. Consider the following examples:


• x=2
• 1 < x < 3 True
• 10 < x < 20 False
• 3 > x <= 2 True
• 2 == x < 4 True
• The comparison is performed between each pair of terms to be evaluated
• For instance in the first example, 1<x is evaluated to True AND x<2 is evaluated

13
Membership operators: in and not in

• in evaluates to True if it finds a variable in a specified sequence and false


otherwise
• not in evaluates to False if it finds a variable in a sequence, True otherwise
• Example:
• 'good' in 'this is a very bad example' False
• 'good' not in 'this is a very bad example' True
• Revisiting another example
if day in ["Tuesday", "Friday"] and date==13:
print(" Today is the 13th and it is either Friday or Tuesday! Good luck.")

14
Identity operator: is and is not

• is evaluates to True if the variables on either side of the operator point to


the same object and False otherwise
• is not evaluates to False if the variables on either side of the operator point
to the same object and True otherwise
• Example:
a = 'Hello World!'
b=a
print(b is a)

15
Exercise

• Write a Python program to calculate a dog's age in dog's years using the
following formula:
• For the first two human years, a dog year is equal to 10.5 human years
• After that, each dog year equals 4 human years
• You can assign value to the variable of the dog's age by asking user input
with the following code:
dog_h_age = int(input("Enter the age of the dog in human years: "))
• If the user enter a negative number or zero, just print an appropriate error
message
16
Solution

dog_h_age = int(input("Enter the age of the dog in human years: "))


if dog_h_age < 0:
print("The dog's age must be a number greater than zero")
elif dog_h_age <= 2:
dog_h_age = dog_h_age * 10.5
else:
dog_h_age = 21 + (dog_h_age - 2)*4

print("The dog's age in dog's years is", dog_h_age)

17
Lazy evaluation
know as well as short-circuit evaluations

18
What is lazy evaluation

• If we have the following statement:


if x or y:
pass
• With lazy evaluation if x is true, python does not need to check the
condition of y
• The Python documentation specifies:
• The expression x and y first evaluates x; if x is false, its value is returned;
otherwise, y is evaluated, and the resulting value is returned
• The expression x or y first evaluates x; if x is true, its value is returned;
otherwise, y is evaluated, and the resulting value is returned
19
Code to validate Pythons lazy evaluation

def x():
print('x')
return False

def y():
print('y')
return False

x() and y()


20
Bitwise and vs. and

• Try to run the following code in your IDE


print(0 < 1 & 0 < 2)
print(0 < 1 and 0 < 2)
• Do you get the same result? Why?
• What does 1&0 return?

21

You might also like