CMPT 120 - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

CMPT 120

Description:

Write simple programs that use if statements. Understand and use boolean ... and life everlasting, behind the other only a swift, but painful, death awaits. ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 35
Provided by: johne78
Category:
Tags: cmpt | awaits

less

Transcript and Presenter's Notes

Title: CMPT 120


1
CMPT 120
  • Flow of Control

2
Objectives
  • Write simple programs that use if statements
  • Understand and use boolean expressions
  • Write simple programs that use for loops
  • Write simple programs that use while loops

3
Flow of Control
  • A basic Python program starts, executes each line
    once and then ends
  • This is not very interesting!
  • Does not allow the user to repeat the process or
  • Change the way the process works
  • Generally, programs are more useful if they allow
    for sections of code to be repeated and for
    choices to be made

4
Making Choices
  • Before you stand two doors, behind one are the
    secrets of love, wealth and life everlasting,
    behind the other only a swift, but painful, death
    awaits. These doors are guarded by two djinns,
    brothers that are both cursed by the gods, one to
    utter only the truth, the other to speak naught
    but lies. Before choosing a door you may ask one
    of the djinns one question, and one only, mark
    you. What is your question?

5
My Answer Is
  • If I asked your brother which door leads to the
    secrets of love, wealth and life everlasting what
    would he answer?
  • I would then take the other door

6
Decisions
  • It is often useful to change the way a program
    executes based on the result of a choice
  • if statements allow a program to branch
  • if a given condition is true then one set of
    statements is executed
  • otherwise (else) a different set of statements is
    executed

7
if Statement Anatomy
if age lt 19 print "No beer for
you!" else beer_consumed beer_consumed 1
keywords
8
if Statement Anatomy
if age lt 19 print "No beer for
you!" else beer_consumed beer_consumed 1
condition must evaluate to true or false
9
if Statement Anatomy
if age lt 19 print "No beer for
you!" else beer_consumed beer_consumed 1
10
Conditions
  • An if statement requires a condition
  • A condition is a boolean expression that must
    evaluate to either true or false
  • Typically, conditions compare two values
  • These values can be constants, variables or
    methods that return values
  • The comparisons are made with a comparison
    operator

11
Comparison Operators
12
Assignment versus Equality
  • The operator is the assignment operator and not
    the test for equality
  • x 12 assigns 12 to the variable x
  • The operator is the test for equality
  • x 12 tests to see if 12 is stored in x
  • Python will not allow you to put an assignment in
    a condition in an if or while statement
  • So if x 12 will cause an error in Python
  • In other programming languages assignment is
    permitted in if statements so be careful

13
Logical Operators
  • an and expression is true if, and only if, both
    operands are true
  • 3 lt 5 and 7 gt 8
  • is False
  • an or expression is true if either of the
    operands are true
  • 3 lt 5 or 7 gt 8
  • is True
  • not is the negation operator, not x is true if x
    is false, and false if x is true
  • not(3 lt 5 and 7 gt 8)
  • is True

14
A Bit of Python Shorthand
  • It is often necessary to see if a value falls
    within a particular range
  • e.g. is the variable age between 19 and 65
  • How can we write this condition in Python?
  • if age gt 18 and age lt 66 or
  • if 18 lt age lt 66
  • Warning! This shorthand may not work reliably in
    other programming languages.

15
Truth Tables
  • Boolean expressions can be evaluated in truth
    tables
  • The symbol ? represents and
  • The symbol ? represents or
  • The symbol ? represents not

16
Boolean Expressions Examples
  • x lt y (x 5 and y 15)
  • True
  • x gt y or x gt z (x 7, y 8 and z 3)
  • True
  • x gt y and x lt len(s) (x 7, y 4 and s
    'cheese')
  • False
  • not(x 13 ! 7) (x 19)
  • False
  • (12 gt 12 or not(33 lt 22)) and 11 13 24
  • True

17
Rules of Precedence
  • Operators are shown highest precedence first
  • Operators with the same precedence are evaluated
    from left to right
  • Note that comparisons are chained together with
    implicit ands

18
Code Blocks in Python
  • The code that is executed when a condition is
    true is indicated by indenting
  • After an if statement indent the code that should
    execute if the condition is true
  • Stop indenting to indicate that the if statement
    is ended
  • The indented code is referred to as the body of
    the if statement

19
Using else Statements
  • An if can be followed by an else
  • The (indented) code following the else statement
    is executed if the condition in the if statement
    is false
  • What if you want more options?
  • e.g. if you want to see if the user entered yes
    or no you should probably check to see if they
    entered an invalid response (e.g. maybe)
  • Use an elif statement

20
The elif Statement
  • elif is an abbreviation of else if. It allows
    conditions to be chained together.
  • You can have as many elif statements as you like
    but they must be preceded by an if statement
  • There can only be one else statement and it must
    be the last statement in the chain
  • In a set of if, elif, , elif, else statements
    exactly one branch will be executed

21
elif Example
def get_grade(score) grade 'F' if score gt
85 grade 'A' elif score gt 70 grade
'B' elif score gt 55 grade 'C' return grade
22
Nested if statements
  • if statements can be nested within each other
  • The structure of a nested if statement is
    indicated by the indentation
  • So be careful!
  • Sometimes nested if statements can be replaced by
    using conditions of greater complexity

23
Loops
  • We often want programs to repeat a process
  • Either as part of an algorithm (like sorting)
  • Or to give the user an opportunity to continue
    using the program
  • There are two types of loops
  • for loops (counting loops, or definite iteration)
  • while loops (conditional loops, or indefinite
    iteration)

24
Iteration
  • A loop statement consists of the controlling
    statement and a body
  • Like if statements the body is indicated by
    indentation
  • When a loop is executed it repeats (or iterates)
    the body until the loop is finished
  • The loop statement (either for or while)
    determines when the iteration stops

25
Iteration with for Loops
  • for loops can be used to repeat the code in the
    body of the loop a given number of times
  • In Python for loops iterate over a range of
    values
  • The syntax allows data structures with multiple
    elements to be easily iterated over
  • For counting loops use the range function

26
ook, ook, ook!
  • Here's some code that gets the user to say how
    many times they want ook to be printed

n int(raw_input("How many 'ook's? ")) for i in
range(n) print 'ook'
27
The for Loop Exposed
  • The range function can be used to create for
    loops that iterate a fixed number of times
  • In fact the process is a little more complicated
    than that
  • Let's modify the ook loop a little
  • It now prints 0 to n by each of the ooks, note
    that it is necessary to convert i (an integer) to
    a string (using the str function) so that it can
    be concatenated it with the ooks

for i in range(n) print str(i) ' ' 'ook'
28
The range function
  • So what does the range function actually do?
  • It returns a list of items as identified by the
    arguments to the range
  • range(10) returns 0,1,2,3,4,5,6,7,8,9
  • range can take other arguments to return lists
    that dont start at 0 and where the values dont
    increase by 1
  • range(-3,5) returns -3,-2,-1,0,1,2,3,4
  • range(8,0,-1) returns 8,7,6,5,4,3,2,1
  • The second argument specifies (one after) the end
    point of the list, the third argument specifies
    the step

29
Re-visiting for Loops
  • Consider for i in range(10,0,-1)
  • The loop will repeat a number of times equal to
    the number of items in the list returned by the
    range function (10 in this case)
  • Each time through the loop, the variable i is
    assigned the value of the next item in the list
    returned by the range function (10,9,8,7,6,5,4,3,
    2,1 in this case)
  • In fact, Python for loops can iterate through the
    items in any sequence (for example, strings)
  • We'll cover this in more detail later in the
    course

30
while loops
  • for loops are very useful for repeating a certain
    number of times, or (particularly in Python) for
    iterating through a sequence
  • But the user (or programmer) needs to know how
    many times the loop is going to repeat before it
    starts
  • It would be useful to have another type of loop
    that repeats until we want it to stop
  • when we are done or
  • when some condition is no longer true

31
How much have you spent?
  • Let's write a loop to add up the value of a stack
    of DVDs
  • Presumably we don't want to count the number of
    DVDs there are first (there's no guarantee the
    count will be correct!)
  • Instead it makes more sense to just keep entering
    amounts until we run out of DVDs

msg "What is the cost (type 'done' to quit)?
" total 0.0 cost raw_input(msg) while cost !
'done' total float(cost) cost
raw_input(msg) print 'the total cost of the DVDs
equals', total
32
while Loop Example Notes
  • Note that, in the example, we needed input before
    entering the while loop
  • The request for input is then repeated inside the
    loop to ensure that it terminates
  • Note this line total float(cost)
  • The operator assigns the value of the
    (original) contents of total added to float(cost)
  • It is synonymous to total total float(cost)
  • It is necessary to convert cost to a float
    because raw_input returns a string
  • Adding a string to a float would cause an error

33
Iteration with while Loops
  • while loops are used to repeat the body of the
    loop until the while condition is false
  • The while condition must be a boolean expression
    that evaluates to true or false
  • This is just like the condition in the if
    statement
  • Make sure that the condition becomes false
    eventually or the loop will never end!
  • type control-c to escape from an infinite loop

34
Using while loops
  • The while loop condition should change (or at
    least have the possibility of changing) in the
    loop body or the loop will repeat infinitely
  • Using the break command in a (for or while) loop
    will quit the loop regardless of how many time it
    has repeated
  • If the while condition is false the first time
    through the loop the body will not be executed at
    all
  • Python does not implement do while loops
Write a Comment
User Comments (0)
About PowerShow.com