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

EECS 1015

Introduction to Computer Science and Programming

Topic 4
Control Structures
(if-statements and loops)

Fall 2021
Michael S. Brown
EECS Department
York University

EECS1015 – York University -- Prof. Michael S. Brown 1


So far . .
• So far, our programs have been boring from a coding point of view

• Our programs execute a statement, then move to the next


statement, and so on until the last statement. Statement 1
• We call this a "linear flow"
• Statements are just performed one after the other
Statement 2

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

True False False

Statement Statement Statement

Statement Statement Statement


1
Statement
Power of flow control 1 2 3
Possible combinations
of statements with
flow control.
Statement
Statement Flow shown by dotted
Possible combinations
lines.
of statements with
no flow control?
Condition
Statement
Flow shown by Statement Statement
red dotted line.
Statement
Statement Statement
Statement
`
Condition Statement
Statement
Statement Statement
Statement
Statement
Statement Statement
Condition
Statement
Condition Statement
Statement
Statement
Statement Flow control allows your program to be so much
EECS1015 – York University -- Prof. Michael S. Brown 4
more interesting and powerful.
Goal of this lecture
• Introduce you to Booleans expressions and simple Boolean algebra
(and, or, not)
• These are the "conditions" for our flow control

• Introduce you to flow control via if-statements (if/if-else/if-elif-else)

• Introduce you to flow control via loop-statements (while/for)

• Continue to help you think like the interpreter

EECS1015 – York University -- Prof. Michael S. Brown 5


Part 1: Booleans, Boolean Expressions
and
Relational Operators

EECS1015 – York University -- Prof. Michael S. Brown 6


Boolean: True or False
• Flow control relies on the evaluation of some True/False condition
• Results that are only in the form True or False are called Booleans

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"

EECS1015 – York University -- Prof. Michael S. Brown 7


Relational operators in Python
Equality* Equals: a == b
operators
Not Equals: a != b
Less than: a < b
Relational* Less than or equal to: a <= b
operators Greater than: a > b
Greater than or equal to: a >= b

These operators all return Boolean (True/False) results.

Why is it called Boolean?


*These can all be considered relational operators, Named after English Mathematician
some resources may classify (== and !=) as equality
George Boole who, in the mid 1800s,
operators.
created a branch of mathematics
EECS1015 – York University -- Prof. Michael S. Brown now known as Boolean algebra. 8
Try some examples
a = 5
b = -1 To the Python interpreter, relational operators,
print( a == b ) like math operators, are treated as
print( a != b ) expressions and must be evaluated to
print( a < b ) compute a reslut. In this case, the result only
print( a > b ) has two possible values (True or False).
print( a <= b )
print( a >= b )

False
True
False
True
False
True

https://trinket.io/python/c4e16965f0

EECS1015 – York University -- Prof. Michael S. Brown 9


Thinking like the interpreter (1/4)
Let's consider this code and explore how the interpreter would process it.

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

Lines 1&2: bind variables to integer objects 5 and -1


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

EECS1015 – York University -- Prof. Michael S. Brown 10


Thinking like the interpreter (2/4)
Step by step evaluation of line three. For math operators you should all know this by now.

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 )

List of variables Data/Objects stored in memory


a 5 (integer)
b -1 (integer)
result1 -5 (integer)
result2

EECS1015 – York University -- Prof. Michael S. Brown 11


Thinking like the interpreter (3/4)
Relational operators are evaluated just like math operators. The only difference is the output
is a Boolean.
line 4: result2 = (a <= b)
a = 5
result2 = (a <= b)
b = -1 step1: realize an expression to handle
step2: replace a with bound data result2 = (5 <= b)
result1 = a * b
step3: replace b with bounda data result2 = (5 <= -1)
result2 = (a <= b)
step4: perform <= operator (results in new object) result2 = 5 <= -1
print( result1 )
step5: bound variable result to new object result2 = False
print( result2 )

List of variables Data/Objects stored in memory


a 5 (integer)
b -1 (integer)
result1 -5 (integer)
result2 False (Boolean)

EECS1015 – York University -- Prof. Michael S. Brown 12


Thinking like the interpreter (4/4)
Relational operators are evaluated just like math operators. The only difference is the output
is a Boolean.
lines 5 & 6: print bound data in bound variables
a = 5
b = -1 List of variables Data/Objects stored in memory
result1 = a * b
a 5 (integer)
result2 = (a <= b)
print( result1 ) b -1 (integer)
print( result2 ) result1 -5 (integer)
result2 False (Boolean)

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: ")

result = float(x.strip()) >= 2 * float(y.strip())

print(" Is x twice as big as y? : %r " % (result) )

%r is symbol for printing True/False (an other data types)

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

EECS1015 – York University -- Prof. Michael S. Brown 14


Python operator precedence - revisited
We now need to include function calls, method calls, indexing, slicing, and equality/condition operators.
We will discuss not, and, and or shortly.

Operator Highest to lowest


() Parentheses
x[index], x[index:index], func(), x.methods() Indexing, Slicing, function calls, method calls
** Exponent
*, /, //, % Multiple, divide, integer divide, modulus
+, - Plus, minus
==, !=, >=, <=, >, < Equality operators (conditionals)
equals ==, not equal !=, greater than or equal to >=,
less than or equal to <=, greater than > , less than <
not Boolean NOT operator
and Boolean AND operator
or Boolean OR operator

EECS1015 – York University -- Prof. Michael S. Brown 15


Mixing with other math operators
x = input("Enter a number x: ") List of variables Data/Objects stored in memory
y = input("Enter a number y: ")
result = float(x.strip()) >= 2 * float(y.strip()) x " 10" (string)
y
Enter a number x: 10 result "2 " (string)
Enter a number y: 2 True (Boolean)

Think like the interpreter:


step 1: see there is an expression to handle result = float(x.strip()) >= 2 * float(y.strip())
step 2: access string object for x result = float(" 10" .strip()) >= 2 * float(y.strip())
step 3: call method strip result = float(" 10" .strip() ) >= 2 * float(y.strip())
step 4: call float function result = float( "10" ) >= 2 * float(y.strip())
step 5: access string object for y result = 10.0 >= 2 * float("2 " .strip())
step 6: call method for strip result = 10.0 >= 2 * float("2 " .strip() )
step 7: call float function result = 10.0 >= 2 * float("2")
step 8: evaluate operator 2 * 2 result = 10.0 >= 2 * 2.0
step 9: evaluate >= operator result = 10.0 >= 4.0
step 10: bind result to result result = True

EECS1015 – York University -- Prof. Michael S. Brown 16


Logical operators – not, and & or
• We also have operators that are made specially for Booleans
• These operators are applied to Booleans and return Booleans

Operator Usage Result type


not not a Boolean
where a is a Boolean
and a and b Boolean
where a and b are
Booleans
or a or b Boolean
where a or b are
Booleans

EECS1015 – York University -- Prof. Michael S. Brown 17


not operator
• Sometimes, we want to express the opposite of an Boolean expression
• This can be done with the not (or negation), such like in spoken
language ("hey, that's not true" – means -> "that is false")
• For example:
x = 3

not (x > 5) not (False) -> True

not (x < 5) not (True) -> False

not (x == 5) not (False) -> True

not (x != 5) not (True) -> False

EECS1015 – York University -- Prof. Michael S. Brown


https://trinket.io/python/72848ed086 18
and & or operators
• Sometimes we want to ask a more complicated question
• We have two Booleans and we want to look at a combined condition

Assume: x = 3

(x > 5) and (x < 10)


False True False and True -> False

(x > 10) or (x < 4)


False True False or True -> True

EECS1015 – York University -- Prof. Michael S. Brown 19


Truth tables (not/and/or)
Assume you have two Boolean values: a and b.
The tables here show you the output of all the possible
combinations of a and b with the Boolean operators and & or.

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

EECS1015 – York University -- Prof. Michael S. Brown 20


Example of and & or
x = int(input("Enter a number x: "))
y = int(input("Enter a number y: "))
This code checks two things.
result1 = (x > 10) and (y > 10)
result2 = (x > 10) or (y > 10) (1) If both entered values are greater
than 10.
print("'and' checks if both x & y are > 10") Check using "and"
print("(%d > 10) and (%d > 10) %r" % (x, y, result1)) (2) If one or more of the values are
greater than 10.
print("'or' checks if at *least* one is > 10") Check using "or"
print("(%d > 10) or (%d > 10) %r" % (x, y, result2))
Play around with the trinket code. You
can verify the table on the previous
slide. As a computer science
student you will use and, or, and
Enter a number x: 10 not often. Memorize the truth
Enter a number y: 11 tables.
'and' checks if both x & y are > 10
(10 > 10) and (11 > 10) False
'or' checks if at *least* one is > 10 https://trinket.io/python/bfc9587ddd
(10 > 10) or (11 > 10) True
EECS1015 – York University -- Prof. Michael S. Brown 21
Relational operators with strings
• You can also use <=, <, >, >=, !=, and == with Strings
• In this case, Lexicographical order is applied
• Think of looking up a word in the dictionary. Words in a dictionary are in
Lexicographical order.
• Lexicographical order for Python works like this, from smallest to be
biggest
smaller ' ' 0-9 A-Z _ a-z larger

space digits uppercase underscore lowercase

' 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'

EECS1015 – York University -- Prof. Michael S. Brown 22


Comparing strings
x = input("Input a letter between A-Z: ")
result = x > "A" and x < "Z"
print("Is %s > 'A'? %r" % (x, x > "A"))
print("Is %s < 'Z'? %r" % (x, x < "Z"))
print("%s is between A-Z? %r" % (x, result)) This code helps you understand
comparisons with strings.
word1 = input("Input word1: ")
word2 = input("Input word2: ") Play around with the trinket code.
You can verify the table on the
print("'%s' < '%s' %r" % (word1, word2, word1 < word2))
previous slide.
print("'%s' == '%s' %r" % (word1, word2, word1 == word2))
As a computer science student you
will compare strings often. It is good
Input a letter between A-Z: B
to understand lexicographical
Is B > 'A'? True
ordering.
Is B < 'Z'? True
'B' is between A-Z? True
Input word1: Toronto
Input word2: Toronto
'Toronto' < 'Toronto' False
'Toronto' == 'Toronto' True https://trinket.io/python/7e2a0ec795

EECS1015 – York University -- Prof. Michael S. Brown 23


Be aware of logic errors
• Logic errors are not syntax errors or run-time errors
• Logic errors is where you make a mistake in your reasoning
• For example, see below:

Can this statement ever be True?


This is a logic error that only has one outcome.
((y * x) > 0) and (y==0)
It will always be false no matter what x and y are.

Recall: != means not equal too. (same as not y == 5)


(y != 5) or (y != 6) Can this statement ever be False?
If y is 5, then it can't be 6.
If y is 6, then it can't be 5.
This is a common logic error that only has one outcome - True.

EECS1015 – York University -- Prof. Michael S. Brown 24


Recap: Boolean expressions
• Expressions that evaluate to either True or False
• This can be equality operators (>, >=, ==, so on) with numbers or
strings
• Some functions and methods also return Booleans (e.g.,
"string".isupper()
• Booleans also have their own operators: and, not, and or
- You need to memorize the truth tables on slide 20

EECS1015 – York University -- Prof. Michael S. Brown 25


Part 2: If-statements

EECS1015 – York University -- Prof. Michael S. Brown 26


if-statement and its variations
Python has several variations of the if-statement. We will refer to all of
this as if-statements

• if
• if-else
• if-elif
• if-elif-else

EECS1015 – York University -- Prof. Michael S. Brown 27


Flow control with the if-statement
• The if-statement
Statement

Statement
If condition is True
Program Flow

Condition Statement

Statement Statements inside if-body


If statement is False
Statement

Statement

EECS1015 – York University -- Prof. Michael S. Brown 28


Python if-statement syntax
statement Important: There must be a colon
after the Boolean expression.

Important: The if 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 if-statement.
same amount. statement These statements are performed only
if the Boolean is true.

x = input("Enter number: ")


x = int(x)

if (x % 2) == 0:
print("{} is even!".format(x))

print("x % 2 == {}".format(x % 2))

https://trinket.io/python/36e767753a
EECS1015 – York University -- Prof. Michael S. Brown 29
Indenting your if-statement

There is no rule how much you need to indent,


as long as the indentation is always the same.
A common convention is to use 4 spaces.

An IDE like PyCharm will do the indentation


for you. The next line here automatically
starts indented.

Even trinket will do it for you. Trinket


uses 2 spaces for indentation.

EECS1015 – York University -- Prof. Michael S. Brown 30


Flow control with the if-statement
• The if-statement
Statement
print("Hello Human")
Statement
ans = input("Is today your birthday (Y/N)? ") If condition is True

if (ans.upper()=="Y"): Condition Statement


print("Let me be the first")
Statement
print("to wish you a ")
If statement is False
Statement
print("HAPPY BIRTHDAY!")

print("I hope you have a wonderful day.") Statement

https://trinket.io/python/24a88e272f

EECS1015 – York University -- Prof. Michael S. Brown 31


Tracing a programming
• Let's walk through the flow of this simple program
• We call this tracing
Think like the interpreter
(I won't show variables and memory this time)
0: print("Hello Human")
1: ans = input("Is today your birthday (Y/N)? ")
2: if (ans.upper()=="Y"):
line 0: print out string
3: print("Let me be the first") line 1: get string input, bind it to variable ans
4: print("to wish you a ") line 2: if (ans.upper()=="Y"):
5: print("HAPPY BIRTHDAY!")
6: print("I hope you have a wonderful day.") Let's walk though this line step by step like the interpreter
-- see next slide-

EECS1015 – York University -- Prof. Michael S. Brown 32


Tracing a programming
0:print("Hello Human") Think like the interpreter
1: ans = input("Is today your birthday (Y/N)? ")
(I won't show variables and memory this time)
2: if (ans.upper()=="Y"):
3: print("Let me be the first")
4: print("to wish you a ") if (ans.upper()=="Y"):
5: print("HAPPY BIRTHDAY!")
6: print("I hope you have a wonderful day.")
Assume user typed in "y" and this is bound to ans.

step 1: see there is an expression if (ans.upper()=="Y"):


step 2: access string object if ("y".upper()=="Y"):
step 3: apply upper method (results in new string) if ("y".upper()=="Y"):
step 4: see if new upper string == "Y" – returns Boolean if ("Y" =="Y"):
step 5: Because condition is True, flow control allows if (True):
lines 3-5 of the code to execute. flow of program includes
lines 3-5!

EECS1015 – York University -- Prof. Michael S. Brown 33


Tracing a programming
0:print("Hello Human") Think like the interpreter
1: ans = input("Is today your birthday (Y/N)? ")
(I won't show variables and memory this time)
2: if (ans.upper()=="Y"):
3: print("Let me be the first")
4: print("to wish you a ") if (ans.upper()=="Y"):
5: print("HAPPY BIRTHDAY!")
6: print("I hope you have a wonderful day.")
Assume user typed in "N" and this is bound to ans.

step 1: see there is an expression if (ans.upper()=="Y"):


step 2: access string object if ("N".upper()=="Y"):
step 3: apply upper method (results in new string) if ("N".upper()=="Y"):
step 4: see if new upper string == "N" – returns Boolean if ("N" =="Y"):
step 5: Because condition is False, flow control skips if (False):
lines 3-5 in the if-block and continues at line 6. flow of program moves to
the lines after the if-block.
So, line 6 executes next.

EECS1015 – York University -- Prof. Michael S. Brown 34


Flow control – 2 possible outcomes
• The if-statement
Statement
print("Hello Human")
Statement
ans = input("Is today your birthday (Y/N)? ") If condition is True

if (ans.upper()=="Y"): Condition Statement


print("Let me be the first")
Statement
print("to wish you a ")
If statement is False
Statement
print("HAPPY BIRTHDAY!")

print("I hope you have a wonderful day.") Statement

https://trinket.io/python/24a88e272f

EECS1015 – York University -- Prof. Michael S. Brown 35


Python's IndentationError
• All lines of code within an if-statement block must have the same
indentation!

print("Hello Human") print("Hello Human")


ans = input("Is today your birthday (Y/N)? ") ans = input("Is today your birthday (Y/N)? ")
if (ans.upper()=="Y"): if (ans.upper()=="Y"):
print("Let me be the first") print("Let me be the first")
print("to wish you a ") print("to wish you a ")
print("HAPPY BIRTHDAY!") print("HAPPY BIRTHDAY!")
print("I hope you have a wonderful day.") print("I hope you have a wonderful day.")

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

EECS1015 – York University -- Prof. Michael S. Brown 36


Another example
ticket_price = 1.50
ans = input("What is your age? ")
age = int(ans) Condition here checks to see if age is
if (age < 18): less than 18. If so, a print statement is
print("You qualify for a reduced fare.") performed and a variable value
ticket_price = 0.50 changed.

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

What is your age? 20


Please pay: 1.50
https://trinket.io/python/fe2e23da6f
Condition=False
EECS1015 – York University -- Prof. Michael S. Brown 37
if-else statement
• The if-else statement
Statement

body of else Statement body of if


False True
Statement Condition Statement

Statement Statement

Statement Statement

Statement

EECS1015 – York University -- Prof. Michael S. Brown 38


if-else syntax
statement Important: There must be a colon
after the Boolean expression.
Important: there if Boolean-expression:
must be a colon after statement
else.
statement We call the top the if-block
The else indentation should be
else: the bottom the else-block.
at the same level as statement
the if-block statements. statement Else-block statements should
statement have the same indentation level
as the if-block statements.
x = input("Enter number: ")
x = int(x)

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))

What is your age? 5


You qualify for a reduced fare.
Please pay: 0.50
Condition=True

What is your age? 20


You need to pay the full fare.
Please pay: 1.50 https://trinket.io/python/c8218bc4a2
Condition=False
EECS1015 – York University -- Prof. Michael S. Brown 40
Introduction to random number generator
In order to allow us to do more interesting
import random examples, I'm going to introduce a function that
generates random numbers.
a = random.randint(1,6)
b = random.randint(1,6) In order to do this, we have to import a module
with called "random". At the top of the program
print("Numbers: %d %d " % (a,b)) we add the line "import random"
print("Run program again to get new numbers.")
Using the random module, we can use the
function: random.randint(min, max)

https://trinket.io/python/355f76a7c1 This generate a random integer in the range


Program above min to max, including the numbers min and
is like rolling max.
a pair of dice.
We will talk more about importing later, but right
This is all the possible now, lets use this feature to help make our
outcomes. program more interesting.
41
Another example of if-else
import random
Use random from previous slide
die1 = random.randint(1,6) to simulate rolling two die.
die2 = random.randint(1,6)

print("die1 [%d] die2 [%d] " % (die1, die2))

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...")

Else (the two dice are not 1s), print these


die1 [1] die2 [1]
statements.
SNAKE EYES! WIN 1000 POINTS!

die [2] die2 [6]


YOU LOSE! LOSE 10 POINTS! https://trinket.io/python/2165a9a304
Run program to try again...
EECS1015 – York University -- Prof. Michael S. Brown 42
Nested if-statements
import random

die1 = random.randint(1,6) if-else statement blue


die2 = random.randint(1,6) The else-block has another
if statement! This is
print("die1 [%d] die2 [%d] " % (die1, die2)) perfectly value.

if (die1==1) and (die2==1): Note that the 2nd if-else


print("SNAKE EYES! WIN 1000 POINTS!") needs to also be indented
else: the same level as the if-
if (die1==1) or (die2==1): block.
print("ALMOST! One die is 1!")
print("Run program to try again...") The new 2nd if-statement
else: needs to be indented.
print("YOU LOSE! LOSE 10 POINTS!")
print("Run program to try again...")

https://trinket.io/python/9e7b32287a

EECS1015 – York University -- Prof. Michael S. Brown 43


"Nested" if statements
Statement

Statement

body of else Condition body of if


The body
False True
can be any Statement Statement
valid Python
statements.
Statement Statement
including another
if-statement
Statement Statement
See next slide.
Statement

Why is it called Nested? It’s called “nested” because you are putting an IF Statement
inside another IF Statement.

if condition [if-block] else [ if condition [if-block] else [else-block] ]


44
Nothing special about nested ifs
Statement

Statement

else-block If condition is True


Condition
Condition Statement

Statement
else-block If condition is True

Statement Statement Statement

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

• So common, that Python (and other languages) have another


variation call the if-elif-else statement

EECS1015 – York University -- Prof. Michael S. Brown 46


if-elif-else Statement

• Python also allows Condition1


if condition True
Statement
a if-elif-else statement False
elif True Statement
Condition_2 Statement


• elif is short for else if Statement
Statement

False elif True


else False Condition_last
Statement Statement
Statement

Statement
Statement

Statement
Statement

Statement`

Statement

EECS1015 – York University -- Prof. Michael S. Brown


47
if-elif-else syntax
statement

Important: there if Boolean-expression1:


must be a colon after the if-block
statement if expression1 is True
elif and else lines
statement
The else indentation should be elif Boolean-expression2: elif-block
at the same level as statement if expression1 is False
the if-block statements. statement and expression2 is True
elif Boolean-expression3:
statement (you can 1 or more elif)
statement elif-block
else: if expression2 is False
statement and expression3 is True
statement
if last elif expression is False,
statement
perform this else-block

EECS1015 – York University -- Prof. Michael S. Brown 48


if-elif-else
import random

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.

if (die1==1) and (die2==1): Second condition 2, if true


print("SNAKE EYES! WIN 1000 POINTS!") perform elif block, if
elif (die1==1) or (die2==1): condition 2 is False,
print("ALMOST! One die is 1!") perform the else-block.
print("Run program to try again...")
else: Note: This has the identical
print("YOU LOSE! LOSE 10 POINTS!") functionality to the nested
print("Run program to try again...") if-block we just looked at.

https://trinket.io/python/17036ac25f

EECS1015 – York University -- Prof. Michael S. Brown 49


import random
Multiple elif blocks
die1 = random.randint(1,6)
die2 = random.randint(1,6)

print("die1 [%d] die2 [%d] " % (die1, die2))

if (die1==1) and (die2==1): if block (first condition)


print("SNAKE EYES! WIN 1000 POINTS!")
elif (die1==1) or (die2==1): elfi block (test 2nd condition)
print("ALMOST! One die is 1!")
print("Run program to try again...")
elif (die1+die2 >= 10): elfi block (test 3 condition)
print("TEN AND OVER! WIN 100 POINTS!")
else:
print("YOU LOSE! LOSE 10 POINTS!") all are false, perform else
print("Run program to try again...")

https://trinket.io/library/trinkets/4174fc0d82

EECS1015 – York University -- Prof. Michael S. Brown 50


You don't have to have an else
import random
Just like the if statement, you don't
have to have an else.
die1 = random.randint(1,6)
die2 = random.randint(1,6)
See this example, else block has been
removed.
print("die1 [%d] die2 [%d] " % (die1, die2))

if (die1==1) and (die2==1):


if block (first condition)
print("SNAKE EYES! WIN 1000 POINTS!")
elif (die1==1) or (die2==1):
elfi block (test 2nd condition)
print("ALMOST! One die is 1!")
elif (die1+die2 >= 10):
print("TEN AND OVER! WIN 100 POINTS!")
elfi block (test 3 condition)
print("Run program to try again...")
There is no else block. This
line of code comes after the
if-elfi statement.
https://trinket.io/python/8ecd21c338
EECS1015 – York University -- Prof. Michael S. Brown 51
pass statement
import random

die1 = random.randint(1,6)
die2 = random.randint(1,6)

print("die1 [%d] die2 [%d] " % (die1, die2))


Sometimes we put in a block, but
if (die1==1) and (die2==1):
we haven't decided what we want
print("SNAKE EYES! WIN 1000 POINTS!")
to do yet. We can put in a
elif (die1==1) or (die2==1):
"pass" statement that moves
pass
to the end of the statement.
elif (die1+die2 >= 10):
print("TEN AND OVER! WIN 100 POINTS!")
You can think of pass as an "empty"
or "null" block.
print("Run program to try again...")

die1 [6] die2 [1]


(die1==1 or die2==1) True
do nothing (pass)
https://trinket.io/python/9edf34e8c8
EECS1015 – York University -- Prof. Michael S. Brown 52
Common errors with if-statement
ticket_price = 1.50
ans = input("What is your age? ")
age = int(ans)
if (age < 18) One common error for new programmers
print("You qualify for a reduced fare.") is to forget the : after the if or elfi or else.
ticket_price = 0.50
else
This will cause a syntax error.
print("You need to pay the full fare.")

print("Please pay: %.2f" % (ticket_price))

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)

• These control structures can be nested multiple times.

EECS1015 – York University -- Prof. Michael S. Brown 54


Part 3: Loops

EECS1015 – York University -- Prof. Michael S. Brown 55


Repetition Structures (Loops)
• Repetition Structures
• Allow a program to repeat an action while a condition is True
• Using while loop
• Action(s) contained within the body of the loop
• Condition should evaluate to false at some point
Condition
• Otherwise infinite loop and program hangs
True

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**")

EECS1015 – York University -- Prof. Michael S. Brown https://trinket.io/python/5981a1e979 57


Simple example with the dice
import random

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!

EECS1015 – York University -- Prof. Michael S. Brown


https://trinket.io/python/0d3dbce95b 58
Another example – checking input
num = int(input("Enter an even number: "))

while (num % 2 != 0): Keep getting input until


num = input("Enter an even number: ") an even number is entered.
num = int(num)
Note that we have to repeat the
print("Thank you!") outside statement num=input(..)
print("num = %d " % (num) )

Enter an even number: 9


Enter an even number: 11
Enter an even number: 10
Thank you!
num = 10

https://trinket.io/python/e8e679b723

EECS1015 – York University -- Prof. Michael S. Brown 59


Sentinel-Controlled Repetition

num = int(input("Enter an even number: "))

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) )

EECS1015 – York University -- Prof. Michael S. Brown 60


Another common example – fixed loops
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
i = 1 important to convert this to an
while (i <= num): integer.
prompt = "Enter student %d grade " % (i)
grade = float(input(prompt)) Create two variables, sometime put
gradeTotal = gradeTotal + grade in the sum and a counter variable (i).
i = i + 1
while the counter is less than our
avg = gradeTotal / num number, ask for the grade, add this to
print("Class average %.2f " % (avg)) the sum. Update our counter
variable.
Enter number of students: 4
Afterwards, compute average
Enter student 1 grade: 80.99
(sum/num) and print it out.
Enter student 2 grade: 95.70
Enter student 3 grade: 65.00
Enter student 4 grade: 75.00
Class average 79.17 https://trinket.io/python/84b6ae7ed8
EECS1015 – York University -- Prof. Michael S. Brown 61
For loop
A range of values, or a list of items.
• The previous example is [0, 1, 2, 3, 4, 5, 6, …., 9]
*so* common, that Condition: still
have items in the
virtually all language list?
support a special version process item
for a fixed number of
Statement 1
loops Out or range repeat
(no more items) for all
Statement 2 items
• The for-loop
Statement 3

Statement 2
advance to next item in the list
[0, 1, 2, 3, 4, 5, 6, …., 9]

EECS1015 – York University -- Prof. Michael S. Brown 62


For-loop syntax
statement Important: There must be a colon
after the Boolean expression.
Important: The for var in RANGE/LIST:
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 for-statement
same amount. These statements are performed for each
statement
item in the range or list. After all
statement statements in the block have been perform
the next item in the list is used.

num = input("Enter number: ") Range statement creates a list,


num = int(num) starting from 1 to num, but not
items = range(1,num+1) including num – so I had to add a plus 1.
See next slide for more details.

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.

syntax examples resulting sequence


range(stop) range(10) 0,1,2,3,4,5,6,7,8,9
range(start,stop) range(5,17) 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
range(10,2) empty sequence
range(start,stop,step) range(2,10,2) 2, 4, 6, 8
range(10,0,-1) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

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.

avg = gradeTotal / num range function creates sequence of


print("Class average %.2f " % (avg)) numbers to loop through. We do not
need to have counter logic like the
while condition (i=i+1)
Enter number of students: 4
Afterwards, compute average
Enter student 1 grade 80.99
(sum/num) and print it out.
Enter student 2 grade 60.70
Enter student 3 grade 75.00
Enter student 4 grade 88.88 https://trinket.io/python/dbe2b02965
Class average 76.39
EECS1015 – York University -- Prof. Michael S. Brown 65
Another example
print("---")
for counter in range(7):
print(counter)
print("---")
for counter in range(7):
if (counter % 2 == 0): Simple for loop to counter from 0..6.
print(counter)
For loop has an if-statement.
--- This only prints out the even numbers. (Yes,
0 we could have created a range(0,7,2), but I
1 want you to see adding if-statements in a
2 loop).
3
4
5
6
---
0
2 https://trinket.io/python/e55a0c6f55
4
EECS1015 – York University -- Prof. Michael S. Brown 66
6
Nested blocks indentation
print("---")
for counter in range(7):
print(counter)
print("---")
Each block requires for counter in range(7):
indentation. These if (counter % 2 == 0):
statements indent once print(counter)
for the for-loop, and else:
again for the if-statement. print("x")

EECS1015 – York University -- Prof. Michael S. Brown 67


break and continue statements
• We can also control the flow inside our out while and for-loops using
the break and continue statements

• break will immediately exit a loop

• continue will return the control of the program to the beginning of


the loop (all remaining statements in the loop are ignored)

EECS1015 – York University -- Prof. Michael S. Brown 68


break statement
• Break immediately exits a while or for-loop, even if the while
condition is still true, or the for-loop still has items in its range
for x in range(1,11): ans = input("Type Q: ")
if (x == 5): while (ans != "Q"):
break if (ans == "-1"):
print(x) break
ans = input("Type Q: ")
print("loop stopped at " + str(x))
print("ans is '%s'" % (ans))

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

EECS1015 – York University -- Prof. Michael S. Brown 69


continue statement
• Continue moves the flow to the start of the loop, all statements after
the continue will be ignored
• If it is a for-loop, the next item in the range/list will be processed
i = 0
for x in range(1,6):
while i < 5:
if (x == 3):
i = i + 1
continue
if i == 3:
print(x)
continue
print(i)

This is very simple to the for-loop example.


Item 3 will not print out, because the print
Just showing continue can also be used
statement was ignored due to the continue.
with while.
https://trinket.io/library/trinkets/c3192cda3b
EECS1015 – York University -- Prof. Michael S. Brown 70
Be careful with continue

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)

What would happen if we moved this statement here?

How would you know there is an error?


Would this code print anything after i==3?
https://trinket.io/library/trinkets/c3192cda3b Try it! Modified the code here
EECS1015 – York University -- Prof. Michael S. Brown
to move the statement. 71
Loops in loops
print("Enter -1 to stop the program")
num = int(input("Enter an integer: "))
while (num != -1):
print("-- Squares List --") while loop keeps asking for a
for i in range(1, num+1): number until the user enters -1.
print("%d**2 = %d" % (i, i**2)) Let's call it num.

num = int(input("Enter an integer: ")) Instead the while loop, we have a


for-loop that prints the square of all
print("Thank You!") numbers is 1..num.

Enter -1 to stop the program


Enter an integer: 3
-- Squares List --
1**2 = 1
2**2 = 4
3**2 = 9
Enter an integer: 2 https://trinket.io/python/ab70d8af07
-- Squares List --
1**2 = 1
2**2 = 4
Enter an integer: -1
EECS1015 – York University -- Prof. Michael S. Brown 72
Thank You!
Recap: loops
• We covered the two types of loops or repetition control structure
• While-loops
• For-loops
• You need to be careful with these control structures, if your logic in
your program is not correct, you can get an infinite-loop

• We have only seen some simple examples

• The combination of if-statements and loop-statements are what give


you the ability to make interesting programs.

EECS1015 – York University -- Prof. Michael S. Brown 73


Part 4: Putting it all together

EECS1015 – York University -- Prof. Michael S. Brown 74


Task #1
Guess the number in ten tries
• Your program will generate a random number from [1 to 100]
• The user has ten tries to guess the number
• Each try, we will tell the user if the guessed number is too high or too
low
• Print out "You WIN" if they guess the number before 10 tries
• Otherwise printout "You LOSE" after the 10th wrong guess

EECS1015 – York University -- Prof. Michael S. Brown 75


Solving this task
• What do we know?
1. Generate a random number
2. Input number from the user (we need to convert it to an integer)
3. Keep track of the number to times user has attempted a guess
4. Use a loop statement that will loop up to 10 times, or until the number is guessed
5. We need a condition that checks if guess == number
5. If the number is guessed before 10 tries, we need to print "You Win"
6. If the number is not guessed before 10 tries, we need to print "You Lose"

There a several way to solve this, let's look


at two different solutions.

EECS1015 – York University -- Prof. Michael S. Brown 76


https://trinket.io/library/trinkets/635cdff1f7 Solution #1 First, generate the random number.
Place in variable umber.
import random
print("Let's begin!")
number = random.randint(1,100) Next, perform the first guess outside
the while-loop. Set guess_try to 1.
guess_try = 1 Variable guess is bound to the input.
print("Try #1") Remember to convert it into an integer.
guess = int(input("Guess the number: "))
while (guess != number and guess_try < 10): While loop. Condition guess != number
if (guess < number): and guess_try < 10.
print("Too low.")
else: Inside the loop, if-statement to check if
print("Too high.") we need to print "high" or "low".
guess_try = guess_try + 1
print("Try #" + str(guess_try)) Now, increment guess_try. Ask the
guess = int(input("Guess the number: ")) user again for a number (just like code
before the loop). Back to top of loop!
# Loop is done, decide what to print
if (guess==number): When the loop terminates only if guess
print("YOU WIN . . the number was" + str(number)) number isn't true or we ran out of tries.
else: As a result, we only need to check if
print("YOU LOSE .. the number was" + str(number)) our guess is correct.
EECS1015 – York University -- Prof. Michael S. Brown 77
https://trinket.io/python/7997cdb714 Solution #2 First, generate the random number.
import random Place in variable umber.
print("Let's begin!")
number = random.randint(1,100) generate a for-loop from range(1,11)
[that is 1,.., 10]
for guess_try in range(1,11):
print("Try #" + str(guess_try)) Print Try #, then get input, store in
guess = int(input("Guess the number: ")) variable guess.
if (guess == number):
break If the guess == number, break out of
if (guess < number): the loop.
print("Too low.")
else: Inside the loop, if-statement to check if
print("Too high.") we need to print "high" or "low". On to
the next try.
if (guess==number):
print("YOU WIN . . the number is " + str(number)) The above loop can only terminate if
else: we guessed the number or we reached
print("YOU LOSE .. the number is " + str(number)) 10 tries. So we only need to test if
guess==number.

EECS1015 – York University -- Prof. Michael S. Brown 78


Task #2
Draw a right triangle (using text)
• Ask the user to input a number between 1 and 10
• Check to make sure the input is between 1 and 10, if not, keep asking
• Let's call this input N
• Draw a triangle as follows (e.g., say N is 6)
*
** Draw N lines of text.
First line starts is a string with only one '*'
*** The last line should have N '*'
****
*****
******

EECS1015 – York University -- Prof. Michael S. Brown 79


Solution
Initialize variables we will use.
msg = "Enter a number between 1 and 10: "
We will set N=-1, which is an invalid
N = -1
range.
# loop to ensure input is correct
Use a simple while loop to keep
while N <1 or N > 10:
prompting the user for input
N = int(input(msg))
until the input is correct.
Check the relationship operator correctly.
# draw triangle
for i in range(1,N+1):
Draw triangle using two loops.
output = ""
Outer loop starts from 1 to N+1 (since
for j in range(0,i):
range() is not inclusive of end)
output = output + "*"
print(output)
Inner loop is from 0 to i, where the variable i is the
current outer-loop value.
https://trinket.io/python/0702c9e167 Concatenate a "*" each time to construct
the line to print.

After inner loop is done, print the output


EECS1015 – York University -- Prof. Michael S. Brown 80
Putting it all together
• We looked at two tasks

• First required combination of loops and if statements


• Two solutions
• first solution used a while-loop with condition to check # of tries and if answer was right
• second solution used a for-loop with fixed # of tries, a "break" was used to exit early

• Second task used "nested loops" to print the triangle.


• Outer loop to counter 1 to N
• Inner loop to count 0 to current outer loop value
This type of nest loop is very common – you will see it often.

EECS1015 – York University -- Prof. Michael S. Brown 81


Summary
• We have talked about flow control
• Flow control allows different parts of a program run depending on some Boolean
condition

• As part of this, we needed to used Booleans, relational operators (==, !=,


<, >, …) and logical operators (and, or, not)

• We looked at if-statements (and its variations – if-else, if-elfi, if-elfi-else)


• And special statement "pass"

• We looked at for and while loops


• And special statements such as break and continue, and range()

• These control structures are similar for most programming languages

EECS1015 – York University -- Prof. Michael S. Brown 82

You might also like