EECS 1015: Introduction To Computer Science and Programming Topic 4
EECS 1015: Introduction To Computer Science and Programming Topic 4
EECS 1015: Introduction To Computer Science and Programming Topic 4
Topic 4
Control Structures
(if-statements and loops)
Fall 2021
Michael S. Brown
EECS Department
York University
Statement 3
…
Statement N
EECS1015 – York University -- Prof. Michael S. Brown 2
Flow control and conditional statements
• We will now look at statements that control how the program flows
• This will allow us to make decisions based on some true/false
"condition" There are two main types of conditional statements.
(1) if statements and (2) loop-statements (or iteration) statements
Statement 1 loop-flow
if-flow-control Statement
-control
Statement 2
Statement
True
Condition
Condition
is 5 > 3? True
is 10 < 0? False
x = 5
is x == 4? False why the ==?
Notice that the Since = is already used to mean
condition doesn't "1234".isnumeric() True assignment or binding, we will use ==
have to be to ask the question if something is equal.
mathematical. "hello".isupper() False
Here are Booleans from
the lecture on "Strings"
False
True
False
True
False
True
https://trinket.io/python/c4e16965f0
Before the program even runs, the interpreter knows the following:
a = 5
b = -1 List of variables Data/Objects stored in memory
result1 = a * b a 5 (integer)
result2 = (a <= b)
b -1 (integer)
print( result1 )
result1
print( result2 )
result2
line 3: result1 = a * b
a = 5
result1 = a * b
b = -1 step1: realize an expression to handle
step2: replace a with bound data result1 = 5 * b
result1 = a * b
step3: replace b with bounda data result1 = 5 * -1
result2 = (a <= b)
step4: perform * operator (results in new object -5) result1 = 5 * -1
print( result1 )
step5: bound variable result to new object result1 = -5
print( result2 )
This simple example is to help you see that relational operators are treated similar
to math operators; however, the result is not an integer or float, but a Boolean.
Additional comment:
result2 = (a <= b) --- the () are not needed.
result2 = a <= b --- this is also acceptable and gives the exact same result.
However, because this statement has two = symbols, my personal preference is to place the relational expression in () to
make the
EECS1015 – York
code easier-- to
University read.
Prof. Michael S. Brown 13
Mixing relational with other operators
x = input("Enter a number x: ")
y = input("Enter a number y: ")
Enter a number x: 10
Enter a number y: 2 result = (float(x.strip()) >= 2 * float(y.strip()))
Is x twice as big as y? : True
This expression mixes math operators, methods,
and functions. Let's see how Python will handle this.
https://trinket.io/library/trinkets/1f87354d93
Assume: x = 3
and or
a b a and b a b a or b
False False False False False False
False True False False True True
True False False True False True
True True True True True True
not
a not a
True False
False True
' 9' < '00' True since ' ' is less than '0'
'99' > '00' True since 9 is greater than 0, "99" is larger than "00"
'2A' < '2z' True '2'=='2', but 'A' is smaller than 'z'
'ABC' < 'abc' True uppercase are "smaller" than lower case
'abc' < 'abcd' True less symbols are smaller than more symbols
'abC' < 'abc' True "ab"="ab", but the 'C' is smaller than 'c'
• if
• if-else
• if-elif
• if-elif-else
Statement
If condition is True
Program Flow
Condition Statement
Statement
if (x % 2) == 0:
print("{} is even!".format(x))
https://trinket.io/python/36e767753a
EECS1015 – York University -- Prof. Michael S. Brown 29
Indenting your if-statement
https://trinket.io/python/24a88e272f
https://trinket.io/python/24a88e272f
NOT OK NOT OK
IndentationError (error happens at initial IndentationError (error happens at initial
check of the program by the interpreter) check of the program by the interpreter)
https://trinket.io/python/ad90079950
print("Please pay: %.2f" % (ticket_price)) Note: the () are not needed. However,
I personally find it easier to read the
condition when () are used.
What is your age? 5
You qualify for a reduced fare.
Please pay: 0.50
Condition=True
Statement Statement
Statement Statement
Statement
if (x % 2) == 0:
print("{} is even!".format(x))
else:
print("{} is odd!".format(x))
https://trinket.io/python/a7a09ba2ee
print("x % 2 == {}".format(x % 2))
39
if-else example
ticket_price = 1.50
ans = input("What is your age? ")
age = int(ans)
if (age < 18):
print("You qualify for a reduced fare.")
ticket_price = 0.50 Condition here checks to see if age is
else: less than 18. If true, run the
print("You need to pay the full fare.") statements in the if-block. If false, run
the statements in the else-block.
print("Please pay: %.2f" % (ticket_price))
if (die1==1) and (die2==1): If the dice are both 1s, print you win 1000 points.
print("SNAKE EYES! WIN 1000 POINTS!") (We call two 1's snake eyes because it looks like
else: two eyes")
print("YOU LOSE! LOSE 10 POINTS!")
print("Run program to try again...")
https://trinket.io/python/9e7b32287a
Statement
Why is it called Nested? It’s called “nested” because you are putting an IF Statement
inside another IF Statement.
Statement
Statement
else-block If condition is True
Statement Statement
Statement Statement
Statement
Statement
EECS1015 – York University -- Prof. Michael S. Brown 45
Nested ifs and the if-elif-else
• Nested if statements are very common
…
• elif is short for else if Statement
Statement
Statement
Statement
Statement
Statement
Statement`
Statement
die1 = random.randint(1,6)
die2 = random.randint(1,6)
If first first condition1 is
print("die1 [%d] die2 [%d] " % (die1, die2)) True, the perform if block.
https://trinket.io/python/17036ac25f
https://trinket.io/library/trinkets/4174fc0d82
die1 = random.randint(1,6)
die2 = random.randint(1,6)
ticket_price = 1.50
ans = input("What is your age? ")
age = int(ans)
if (age < 18):
print("You qualify for a reduced fare.")
ticket_price = 0.50 One common error, we leave out
else:
a block. This will cause an indentation error
for the code on the next line.
print("Please pay: %.2f" % (ticket_price))
EECS1015 – York University -- Prof. Michael S. Brown 53
Recap: if statements
• This is a power flow-control mechanism to perform a different set of
statements depending on if a condition is true
• The programmer must ensure the conditions are correct (and don't
contain logical errors)
Statement
False
Statement
Statement
Statement
EECS1015 – York University -- Prof. Michael S. Brown 56
While-loop syntax
statement Important: There must be a colon
after the Boolean expression.
Important: The while Boolean-expression:
statements inside statement One or more statements go here.
the block must all statement This is known part is referred to as a
be indented by the … "block" or the "body" of the while-statment
same amount. statement These statements are performed over
statement and over until the Boolean-expression
is no longer true.
x = input("Enter number: ")
x = int(x)
while x > 0:
print("Count down %d" % (x))
x = x - 1
print("**BOOM**")
die1 = random.randint(1,6)
die2 = random.randint(1,6)
While loop keeps getting random
while (die1 != die2): numbers for die1 and die2 until
print("die1 [%d] die2 [%d] " % (die1, die2)) the two numbers are the same.
die1 = random.randint(1,6)
die2 = random.randint(1,6) What would happen if I forgot these
two lines of code?
# Note that I have to repeat a line of coe - The dreaded infinite loop!
print("die1 [%d] die2 [%d] " % (die1, die2))
print("DOUBLES!")
Note that I have to repeat this
die1 [3] die2 [2] line of code from the loop. Why?
die1 [1] die2 [3]
die1 [3] die2 [3]
DOUBLES!
https://trinket.io/python/e8e679b723
while (num % 2 != 0): This condition acts like a "Guard" (i.e., a sentinel).
num = input("Enter an even number: ") This condition will run as long as this guard is true.
num = int(num) We do not know how long this loop will run.
print("Thank you!")
print("num = %d " % (num) )
Statement 2
advance to next item in the list
[0, 1, 2, 3, 4, 5, 6, …., 9]
for x in items: iterates through each item in the list (or range).
print("Count up %d" % (x)) We have access to the current item using
the x variable.
print("**BOOM**")
63
https://trinket.io/python/a172a8a205
range() function
• Use the range() function to creates a sequence of numbers from start
(inclusive) to stop (exclusive).
• Step size can be used to advance by a different value (or step) than 1.
• If only one parameter is passed to range (e.g., range(10)), start is
assumed to be 0.
https://trinket.io/python/ca83bd5074
EECS1015 – York University -- Prof. Michael S. Brown 64
Previous example with for-loop
num = input("Enter number of students: ") Computing average of a fixed number of numbers.
num = int(num)
gradeTotal = 0 First ask for a number. Very
important to convert this to an
for i in range(1, num+1): integer.
prompt = "Enter student %d grade " % (i)
grade = float(input(prompt)) Create one variables, something to ut
gradeTotal = gradeTotal + grade the gradeTotal (sum) in.
Here we break at item 5, even though Here we break when ans=='-1' even
our range sequence still has items. though the while condition is still True
(e.g., '-1' != 'Q' is True)
https://trinket.io/library/trinkets/b2e34f922b
i = 0 i = 0
while i < 6: while i < 6:
i = i + 1 if i == 3:
if i == 3: continue
continue i = i + 1
print(i) print(i)