Branches and Loops
Download
Report
Transcript Branches and Loops
COSC 1306—COMPUTER
SCIENCE AND PROGRAMMING
PYTHON BRANCHES AND LOOPS
Jehan-François Pâris
[email protected]
STARTING WITH A GAME
Number guessing game
• We use a random number generator to generate
a random number between 1 and 10
• Users are asked to guess the number until they
come with the right value
Number guessing game
• We use a random number generator to generate
a random number between 1 and 10
• Users are asked to guess the number until they
come with the right value
Flow chart
Generate RN n
Input i
False
True
i == n
You win
More about flow charts
• Graphic representation of flow of control
– Loops represented by loops
– Ifs have two branches
True
False
???
Simple if
• If condition :
something
True
condition
False
something
• If tank_empty :
get_gas
If with else clause (I)
False
other stuff
• If condition:
something
else:
other stuff
condition
True
something
If with else clause (II)
• If hungry :
Macdonald
else :
Starbucks
• In either case, you will leave the freeway
While
• while condition :
something
True
condition
False
something
• while stain :
keep_washing
Go back!
How to generate RN
• Import a function from module random
– from random import randint
• randint(min, max)
– generates an integer between min and max
The program (I)
• # guess.py
“”” must guess a random number between
1 and 10
“””
# secret
# guess
The program (II)
• from random import randint
secret = randint (1,10)
guess = -1 # bad guess
while guess != secret :
guess = int(input("Enter your guess: ")
print("You win!")
A better program
• Tells whether guess is too low or too high
• Must consider three cases inside the loop
– Correct guess
– Guess that is too low
– Guess that is too high
The better program (I)
• # guess.py
“”” must guess a random number between
1 and 10
“””
# secret
# guess
from random import randint
secret = randint (1,10)
guess = -1 # bad guess
The program (II)
• while guess != secret :
guess = int(input(“Enter your guess: “))
if guess == secret :
print ("You win!")
else :
if guess < secret :
print ("Too low!")
else:
print ("Too high!")
Using an elif (I)
• Too many nested ifs
if cond-1 :
…
else if cond-2 :
…
else if cond-3 :
…
else
…
Example
while guess != secret :
guess = int(input("Enter your guess: "))
if guess == secret :
print ("You win!")
elif guess < secret : # observe indentation
print ("Too low!")
else:
print ("Too high!")
Using an elif (II)
• With elif, lines align better
if cond-1 :
…
elif cond-2 :
…
elif cond-3 :
…
else
…
Indenting advice
• Python attaches great importance to indenting
– You cannot indent anything that is not inside
• An if, a while, a for, …
• A function declaration or a main function
– Your indentation must be consistent
• Do not mix spaces and tabs