0% found this document useful (0 votes)
13 views33 pages

3 Controls

Uploaded by

tolgaairmakk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views33 pages

3 Controls

Uploaded by

tolgaairmakk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

BUS 601 Python for Analytics

Lecture 3 Control Statements: if


Intro to Python for Computer Science and Data Science, Chapter 3

By Dr. Qi Li

BUS 601
Learning Objectives
• Decide whether to execute actions with the statements
if, if…else and if…elif…else.
• Learn problem-solving skills: understanding problem
requirements, dividing problems into smaller pieces,
developing algorithms to solve problems and
implementing those algorithms in code.
• Develop algorithms through the process of top-down,
stepwise refinement.
• Create compound conditions with the Boolean
operators and, or and not.

BUS 601
Control Statements
• Usually, statements in a program execute in the
order in which they’re written, called sequential
execution.
• Some Python statements enable you to specify
that the next statement to execute may be other
than the next one in sequence, called transfer of
control, or control statements.
– The selection statement
– The iteration statement

BUS 601
Flowcharts
• Graphical representation of an algorithm or a part of one.
• Using rectangles, diamonds, rounded rectangles and small circles
connected by arrows called flowlines.
• Clearly show how forms of control operate.
• Rectangle (or action) symbol indicates any action
• Flowlines show the order in which the actions execute.
• In a flowchart for a complete algorithm, the first symbol is a
rounded rectangle containing the word “Begin.” The last symbol
is a rounded rectangle containing the word “End.”
• In a flowchart for only a part of an algorithm, use small circles
called connector symbols.

BUS 601
Flowchart example
• Flowchart shows a sequential execution:

BUS 601
If Statement Flowchart
• The decision (diamond) symbol contains a condition that can be
either True or False.
• Two flowlines emerging from it:
– One indicates the direction to follow when the condition in the symbol is
True.
– The other indicates the direction to follow when the condition is False.

BUS 601
The if statement: a summary

if true-or-false-condition :
Indented Statement Block, if the
condition is true
Example: if miles > 20000:
print( "Upgrade!" )

Wrong:  Beware!
This is not a true-or-false condition!
if miles:
print( "Upgrade!" )

BUS 601
if Statement
• “A passing grade on an examination is 60”.
• The pseudocode
If student’s grade is greater than or equal to 60
Display 'Passed'

• If the condition is true, 'Passed' is displayed.


• If the condition is false, nothing is displayed.
• Indentation emphasizes that 'Passed' is displayed only if the
condition is true.

BUS 601
Python: if
• Keyword of if,
• Semicolon
• Suite indentation

BUS 601
Indentation tells you important
information!
n= input( "Pick a positive number" )
if n < 0:
print( "I said a positive number!" )
print( "Were you listening?" )
print( "Anyway." )

BUS 601
Summary of comparison operators

if age == 21: equal


if age != 21: not equal
if age < 21: less than
if age > 21: greater than
if age <= 21: less than or equal to
if age >= 21: greater than or equal to

Watch the order: =< and => are not correct here.
Also, no spaces are allowed in the middle of ==, !=, <=, or >=.

BUS 601
Checking equality
• To check if two things are equal, use a double equal sign: ==.

n= int(input( "Pick a lucky number" ))


if n == 13 :
print( "That is not a lucky number!" )

name= input( "What is your name?" )


if name == "Mildred" :
print( "My, what a beautiful name." )

BUS 601
Combining conditions
• if statement with simple conditions:
If your temperature is greater than 98.6, then go to see the
doctor.

• Sometimes a task is to be performed based on multiple


conditions.

If your temperature is greater than 98.6 OR you have a rash on your arm, go
to see the doctor.
If your temperature is NOT greater than 98.6, don’t call in sick to work.
If you are stung by a bee AND you are allergic to bees, go to see the doctor.
If you are stung by a bee AND you are NOT allergic to bees, do not worry!

BUS 601
Logical connective (logical operator)
• In order to perform multiple conditions, logical
connective (symbol or word ) is applied to one or
multiple conditions is a used to connect one or
more simple conditions
• binary connectives
– and: conjunction, e.g., rivers AND salinity
– or: disjunction
• unary connective
– not: negation

BUS 601
Combining conditions with and
if width > 100 and height > 100 :
print ( "Area is greater than 10000 square inches." )

if x > -25 and x < 25 and y > -25 and y < 25 :


print ( "point (x, y) must be inside the rectangle." )

• With and, all of the conditions must be true


• for the expression to be true!
• Unless parentheses are used to group conditions, evaluation is done left-to-right as one
expression.

BUS 601
Combining conditions with or
if age < 0 or age > 120:
print ( "Not human." )

if age < 18 or age > 65 or myName == yourName :


print ( "Not interested." )

• With or, at least one of the conditions must be true for the
expression to be true!

BUS 601
Grouping conditions
if a < b and b < c or c < b and b < a :
print ( "in ascending or descending order" )
if ( a < b and b < c ) or ( c < b and b < a ) :
print ( "in ascending or descending order" )

• The normal order of evaluation of conditional expression is: left-


to-right
• not has higher precedence than and
• and has higher precedence than or
• Parentheses often improve readability and may be used to
override normal evaluation order.
• Try: true or true and false

BUS 601
Watch the phrasing of conditions

Be sure that what you put on either side of the and or or


are both true/false statements:

error!! if age < 15 or > 90:


print "Should you really be driving?"

Correct if age < 15 or age > 90:


print "Should you really be driving?"

BUS 601
Selection Statement
• Three selection statements that execute code based on a
condition—an expression that evaluates to either True
or False:
– if performs an action if a condition is True or skips the action
if the condition is False.
– if…else statement performs an action if a condition is True
or performs a different action if the condition is False.
– if…elif…else statement performs one of many different
actions, depending on the truth or falsity of several
conditions.
• Anywhere a single action can be placed, a group of
actions can be placed.
BUS 601
if-else
• Pseudocode if condition :
– If student’s grade is greater than or equal to what to do if condition is true
60
Display 'Passed'
else :
Else
what to do if condition is false
Display 'Failed'

BUS 601
Concise conditional expression

BUS 601
Multi-way decisions: if-elif-else
if condition A :
...
what to do if condition A is true
...
elif condition B :
...
what to do if condition A is false but B is true
...
elif condition C :
...
what to do if conditions A and B are false but C is true
...
else:
...
what to do if none of the above conditions are true
...

• Else clause is optional


– Handle values that do not satisfy any of the conditions.
– Without an else, if no conditions are True, the program does not execute
any of the statement’s suites.
BUS 601
BUS 601
Elif: Example
if age < 6 :
print ("Not in school yet“)
elif age < 12 :
print ("Elementary school“)
elif age < 15 :
print ("Middle school“)
elif age < 18 :
print ("High school“)
else:
print ("College“)
print ("Hey“)

BUS 601
Listen to the logic of English

If quantity is under The cost is a dollar,


a dozen, the cost is unless the quantity is a
a dollar. Otherwise dozen or more in
it is two dollars. which case it is two
dollars.

if quantity < 12:


cost= 1
else:
cost= 2

Words like "otherwise" and "unless"


suggest if/else logic is needed!

BUS 601
Different ways of coding the same thing

if quantity >= 12: if quantity < 12:


cost= 2 cost= 1
else: else:
cost= 1 cost= 2

This phrasing is preferable.


cost= 2
Why?
if quantity < 12
cost= 1 Simpler, and asks only one
question about the value of
variable quantity, not two.

if quantity < 12:


cost= 1
cost= 1
if quantity >= 12
if quantity >= 12:
cost= 2
cost= 2

BUS 601
Multiway decision vs. multiple decisions

if isSleepy() : if isSleepy() :
print "Sleepy" print "Sleepy"

elif isHungry() : if isHungry() :


print "Hungry" print "Hungry"

elif isAngry() : if isAngry() :


print "Angry" print "Angry"

else : else :
print "Whatever" print "Whatever"

What's the difference?

BUS 601
Nesting
• You can put anything in an if, else, or elif
block, including other if statements, if-
else blocks, etc.
if age < 17:
if rating == "R":
print( "Parent or guardian please" )
elif rating == “X":
print ( "Go away" )
else:
print( “You may enter alone" )

age 19 rating ??? Output: You may enter alone


?

age 16 rating R Output Parent or guardian


please

BUS 601
Practice with multi-way decisions

reply= input( "What color would you like?" )


if reply == "black":
color= black
elif reply == "white":
color= white
elif reply == "blue":
color= blue
else:
print( "I don't know that color. Here is a
color picker." )

BUS 601
Color choice program -- flow diagram

read in variable reply --


the name of a color

reply == no
“black”?

yes reply == no
“white”?

yes reply == no
“blue”?
color = _ color = _
yes
color = _ offer color picker

make and draw picture


in the chosen color

BUS 601
Algorithm
• Any computing problem can be solved by
executing a series of actions in a specific order.
• An algorithm is a procedure for solving a
problem in terms of
– the actions to execute and
– the order in which these actions execute
• Specifying the order in which statements
(actions) execute in a program is called program
control.

BUS 601
Pseudocode
• An informal language that helps you develop algorithms without
having to worry about the strict details of Python syntax.
• Similar to everyday English.
• Helps you “think out” a program before attempting to write it in
a programming language.
• Carefully prepared pseudocode can easily be converted to a
corresponding program.
• Pseudocode normally describes only statements representing the
actions that occur (e.g., input, output or calculations) after you
convert a program from pseudocode to Python and run the
program.

BUS 601
Example

BUS 601

You might also like