control flow revisited

152
Piech + Sahami, CS106A, Stanford University Control Flow Revisited Chris Piech and Mehran Sahami Stanford University Control Flow CS106A

Upload: others

Post on 16-Oct-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Control Flow RevisitedChris Piech and Mehran Sahami

Stanford University

Control Flow

CS106A

Page 2: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Review

Page 3: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Suitcase Analogy

num_students 700 int

num_students = 700

name typevalue

Page 4: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

My computer has space for about 10 billion suitcases

Teeny Tiny Suitcases

700 int

Page 5: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Create, Modify, Use

# Create a variable, of type int# called age with the value 30.age = 32

# Use the value in age (output it)print(“age is: ” + str(age))

# Modify age to be one greater.age = age + 1

Page 6: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Create, Modify, Use

# Create a variable, of type int# called age with the value 30.age = 31

# Use the value in age (output it)print(“age is: ”, age)

# Modify age to be one greater.age = age + 1

Page 7: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

+-

AdditionSubtraction

* Multiplication/ Division

Binary Operators

Page 8: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Cool Example: Carbon Dating

What is the % of natural c14 in your sample? 25

Your sample is 11460.0 years old

Page 9: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Cool Example: Carbon Dating

C14 = 8.8%C14 = 100%

age = K · log⇣ c14

100

<latexit sha1_base64="GGJCQr24+hXhXN9UVN4BtY31pk4=">AAACHHicbZDLSsNAFIYnXmu9VV26GSxC3ZREC7oRSt0IbirYCzSlTKaTdugkE2ZOxBLyIG58FTcuFHHjQvBtnLRdaOsPAx//OYc55/ciwTXY9re1tLyyurae28hvbm3v7Bb29ptaxoqyBpVCqrZHNBM8ZA3gIFg7UowEnmAtb3SV1Vv3TGkuwzsYR6wbkEHIfU4JGKtXOHOBPUBCBizFl/gGu7QvAbtCDrBb44OS6ytCE+pU0sSx7TTzTnqFol22J8KL4MygiGaq9wqfbl/SOGAhUEG07jh2BN2EKOBUsDTvxppFhI7MFh2DIQmY7iaT41J8bJw+9qUyLwQ8cX9PJCTQehx4pjMgMNTztcz8r9aJwb/oJjyMYmAhnX7kxwKDxFlSuM8VoyDGBghV3OyK6ZCYOMDkmTchOPMnL0LztOwYvq0Uq7VZHDl0iI5QCTnoHFXRNaqjBqLoET2jV/RmPVkv1rv1MW1dsmYzB+iPrK8fNOygKQ==</latexit><latexit sha1_base64="GGJCQr24+hXhXN9UVN4BtY31pk4=">AAACHHicbZDLSsNAFIYnXmu9VV26GSxC3ZREC7oRSt0IbirYCzSlTKaTdugkE2ZOxBLyIG58FTcuFHHjQvBtnLRdaOsPAx//OYc55/ciwTXY9re1tLyyurae28hvbm3v7Bb29ptaxoqyBpVCqrZHNBM8ZA3gIFg7UowEnmAtb3SV1Vv3TGkuwzsYR6wbkEHIfU4JGKtXOHOBPUBCBizFl/gGu7QvAbtCDrBb44OS6ytCE+pU0sSx7TTzTnqFol22J8KL4MygiGaq9wqfbl/SOGAhUEG07jh2BN2EKOBUsDTvxppFhI7MFh2DIQmY7iaT41J8bJw+9qUyLwQ8cX9PJCTQehx4pjMgMNTztcz8r9aJwb/oJjyMYmAhnX7kxwKDxFlSuM8VoyDGBghV3OyK6ZCYOMDkmTchOPMnL0LztOwYvq0Uq7VZHDl0iI5QCTnoHFXRNaqjBqLoET2jV/RmPVkv1rv1MW1dsmYzB+iPrK8fNOygKQ==</latexit><latexit sha1_base64="GGJCQr24+hXhXN9UVN4BtY31pk4=">AAACHHicbZDLSsNAFIYnXmu9VV26GSxC3ZREC7oRSt0IbirYCzSlTKaTdugkE2ZOxBLyIG58FTcuFHHjQvBtnLRdaOsPAx//OYc55/ciwTXY9re1tLyyurae28hvbm3v7Bb29ptaxoqyBpVCqrZHNBM8ZA3gIFg7UowEnmAtb3SV1Vv3TGkuwzsYR6wbkEHIfU4JGKtXOHOBPUBCBizFl/gGu7QvAbtCDrBb44OS6ytCE+pU0sSx7TTzTnqFol22J8KL4MygiGaq9wqfbl/SOGAhUEG07jh2BN2EKOBUsDTvxppFhI7MFh2DIQmY7iaT41J8bJw+9qUyLwQ8cX9PJCTQehx4pjMgMNTztcz8r9aJwb/oJjyMYmAhnX7kxwKDxFlSuM8VoyDGBghV3OyK6ZCYOMDkmTchOPMnL0LztOwYvq0Uq7VZHDl0iI5QCTnoHFXRNaqjBqLoET2jV/RmPVkv1rv1MW1dsmYzB+iPrK8fNOygKQ==</latexit><latexit sha1_base64="GGJCQr24+hXhXN9UVN4BtY31pk4=">AAACHHicbZDLSsNAFIYnXmu9VV26GSxC3ZREC7oRSt0IbirYCzSlTKaTdugkE2ZOxBLyIG58FTcuFHHjQvBtnLRdaOsPAx//OYc55/ciwTXY9re1tLyyurae28hvbm3v7Bb29ptaxoqyBpVCqrZHNBM8ZA3gIFg7UowEnmAtb3SV1Vv3TGkuwzsYR6wbkEHIfU4JGKtXOHOBPUBCBizFl/gGu7QvAbtCDrBb44OS6ytCE+pU0sSx7TTzTnqFol22J8KL4MygiGaq9wqfbl/SOGAhUEG07jh2BN2EKOBUsDTvxppFhI7MFh2DIQmY7iaT41J8bJw+9qUyLwQ8cX9PJCTQehx4pjMgMNTztcz8r9aJwb/oJjyMYmAhnX7kxwKDxFlSuM8VoyDGBghV3OyK6ZCYOMDkmTchOPMnL0LztOwYvq0Uq7VZHDl0iI5QCTnoHFXRNaqjBqLoET2jV/RmPVkv1rv1MW1dsmYzB+iPrK8fNOygKQ==</latexit>

Half life constant% of natural c14

Page 10: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14: "))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

* It calculates the age of a C14 sample

Cool Example: Carbon Dating

Page 11: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14: "))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

* It calculates the age of a C14 sample

Cool Example: Carbon Dating

terminal

> python carbondate.py

Page 12: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14: "))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

* It calculates the age of a C14 sample

Cool Example: Carbon Dating

terminal

> python carbondate.py

Page 13: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14: "))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

Page 14: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

50.0pct_left

float

Page 15: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

50.0pct_left

float

0.5

Page 16: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

50.0pct_left

float

-0.69

Page 17: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

50.0pct_left

float

5730.0

Page 18: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50

50.0pct_left

float

5730.0age

float

Page 19: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

Cool Example: Carbon Dating

terminal

> python carbondate.py% of natural c14: 50Sample is 5730.0 years old

50.0pct_left

float

5730.0age

float

Page 20: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Goal1. Be able to use For / While / If in Python

Page 21: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

ReviewWhile/If

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

Page 22: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

ReviewWhile/If

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

Page 23: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

While Loop in Karel

while front_is_clear() :body

if beepers_present() :body

Page 24: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

While Loop Redux

while condition :body

if condition :body

The condition should be a “boolean” which is either True or False

Page 25: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

* It calculates the age of a C14 sample

Cool Example: Carbon Dating

Page 26: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

K = -8266.64

def main():while True:

calculate_age_single_sample()

def calculate_age_single_sample():# ask the user to enter the percent c14 left in their samplepct_left = float(input("% of natural c14 in Sample:"))# calc the ageage = K * math.log(pct_left / 100)# print the resultprint("Sample is " + str(age) + " years old.")

* It calculates the age of a C14 sample

Cool Example: Carbon Dating

Before repeating the body, check if this statement

evaluates to True

Page 27: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

Review

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

While/If

Page 28: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

Review

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

While/If

Page 29: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

front_is_clear()

True

Booleans

Page 30: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

beyonce_is_great()

True

Booleans

Page 31: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

1 < 2

True

Booleans

Page 32: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Operator Meaning Example Value

== equals 1 + 1 == 2 True

!= does not equal 3.2 != 2.5 True

< less than 10 < 5 False

> greater than 10 > 5 True

<= less than or equal to 126 <= 100 False

>= greater than or equal to 5.0 >= 5.0 True

* All have equal precedence

Comparison Operators

Page 33: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Operator Meaning Example Value

== equals 1 + 1 == 2 True

!= does not equal 3.2 != 2.5 True

< less than 10 < 5 False

> greater than 10 > 5 True

<= less than or equal to 126 <= 100 False

>= greater than or equal to 5.0 >= 5.0 True

* All have equal precedence

Comparison Operators

Page 34: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Spot the difference

x = 7 x == 7

Sets the value of a variable named x to be 7. Creates the variable

if it didn't exist.

Checks if a variable named x has the

value 7

Page 35: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

if 1 < 2 :print("1 is less than 2")

num = int(input("Enter a number: "))if num == 0:

print("That number is 0")else :

print("That number is not 0.")

Comparison Operators

Page 36: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")else:

if num > 0:

print("Your number is positive")else:

print("Your number is negative")

If Else Revisited

Page 37: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

Page 38: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

Page 39: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

Page 40: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited“5”

5Enter a number:

Page 41: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited5

5Enter a number:

“5”

Page 42: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited5

5Enter a number: 5num

Page 43: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

5Enter a number: 5num

Page 44: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

5Enter a number: 5num

Page 45: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

5Enter a number: 5num

Your number is positive

Page 46: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

num = int(input("Enter a number: "))if num == 0:

print("Your number is 0 ")elif num > 0:

print("Your number is positive")

else:print("Your number is negative")

If Else Revisited

5Enter a number: 5num

Your number is positive

Page 47: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Conditions in Python

Use while and if statements in Python.

They are the same as in Karel, except that the test can be any

expression that evaluates to True or False

Page 48: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Amazing

Page 49: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Number

Page 50: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92 int

Page 51: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92 int

Page 52: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

50 int

int

Page 53: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

50 int

int

Page 54: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

50 int

int

Page 55: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

50 int

int

Page 56: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

50 int

int

Page 57: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

95 int

int

Page 58: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guess

95 int

int

Page 59: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int95

Page 60: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int95

Page 61: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int95

Page 62: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int95

Page 63: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int92

Page 64: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int92

Page 65: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int92

Page 66: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

secret_number

92

guessin

t

int92

Page 67: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Behind the Scenes-

Page 68: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile ???:

# Report on the old guess# Get a new guess

print("Congrats! The number was: " + str(secret_number))

secret_number

92 int

Page 69: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile ???:

# Repeat some stuff???

print("Congrats! The number was: " + str(secret_number))

Page 70: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile ???:

# Get a new guess

# Report high/low

print("Congrats! The number was: " + str(secret_number))

Page 71: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile ???:

# Get a new guessguess = int(input("Enter a guess: "))

# Report high/low

print("Congrats! The number was: " + str(secret_number))

Page 72: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# Get a new guessguess = int(input("Enter a guess: "))

# Report high/low

print("Congrats! The number was: " + str(secret_number))

Page 73: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")=guess = int(input("Enter a guess: "))

# True if guess is not equecret numberwhile guess != secret_number:

# Report high/low

# Get a new guessguess = int(input("Enter a guess: "))

print("Congrats! The number was: " + str(secret_number))

Page 74: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Guess My Numbersecret_number = random.randint(1, 99)print("I am thinking of a number between 1 and 99...")guess = int(input("Enter a guess: "))# True if guess is not equal to secret numberwhile guess != secret_number:

# True if guess is less than secret numberif guess < secret_number:

print("Your guess is too low")else:

print("Your guess is too high")

print("") # an empty lineguess = int(input("Enter a new guess: "))

print("Congrats! The number was: " + str(secret_number))

Page 75: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

• sentinel: A value that signals the end of user input.– sentinel loop: Repeats until a sentinel value is seen.

• Example: Write a program that prompts the user for numbers until the user types -1, then output the total of the numbers.– In this case, -1 is the sentinel value.

Type a number: 10Type a number: 20Type a number: 30Type a number: -1total is 60

Challenge: Sentinel Loops

Page 76: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Time to shine

Page 77: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

https://us.edstem.org/courses/ 10000/lessons/13552/slides/67360

Type a number: 10Type a number: 20Type a number: 30Type a number: -1total is 60

Page 78: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0while num != -1:

num = int(input("Enter a number: "))total += num

print("total is " + total)

Example: Sentinel Loops

NameError: name 'num' is not defined

Page 79: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

Page 80: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

0 int

Page 81: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

0 int

Page 82: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

0 int

num

2 int

Page 83: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

0 int

num

2 int

Page 84: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

2 int

num

2 int

Page 85: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

2 int

num

2 int

Page 86: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

2 int

num

3 int

Page 87: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

2 int

num

3 int

Page 88: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

2 int

num

3 int

Page 89: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

3 int

Page 90: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

3 int

Page 91: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

-1 int

Page 92: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

-1 int

Page 93: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

-1 int

Page 94: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0num = int(input("Enter a number: "))while num != -1:

total += numnum = int(input("Enter a number: "))

print("total is " + total)

Example: Sentinel Loops

total

5 int

num

-1 int

Page 95: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0while True:

num = int(input("Enter a number: "))if num == -1:

break # immediately exits looptotal += num

print("total is " + total)

Example: Sentinel Loops

Page 96: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# fencepost problem!# ask for number - post# add number to total - fence

total = 0while True:

num = int(input("Enter a number: "))if num == SENTINEL:

break # immediately exits looptotal += num

print("total is " + total)

Example: Sentinel Loops

Page 97: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Operator Example Result

not not (2 == 3) True

and (2 == 3) and (-1 < 5) False

or (2 == 3) or (-1 < 5) True

Can "chain" tests

# is x between 2 and 10?2 <= x and x <= 10

In order of precedence:

Logical Operators

Page 98: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 99: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False5 * 7 >= 3 + 5 * 6 and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 100: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 101: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False35 >= 3 + 30 and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 102: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False35 >= 3 + 30 and not False35 >= 33 and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 103: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False35 >= 3 + 30 and not False35 >= 33 and not FalseTrue and not False

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 104: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False35 >= 3 + 30 and not False35 >= 33 and not FalseTrue and not FalseTrue and True

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 105: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Precedence: arithmetic > comparison > not > and/or5 * 7 >= 3 + 5 * (7 – 1) and not False35 >= 3 + 5 * 6 and not False35 >= 3 + 30 and not False35 >= 33 and not FalseTrue and not FalseTrue and TrueTrue

Precedence Madness

https://docs.python.org/3/reference/expressions.html#operator-totalmary

Page 106: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

George Boole

English Mathematician teaching in Ireland 1815 – 1864Boole died of being too cool

Page 107: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# Store expressions that evaluate to True/Falsex = 1 < 2 # Truey = 5.0 == 4.0 # False

Boolean Variables

x True

boolean

y False

boolean

Page 108: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# Store expressions that evaluate to True/Falsex = 1 < 2 # Truey = 5.0 == 4.0 # False

# Directly set to True/Falseis_sheltering = Trueis_raining = False

Boolean Variables

Page 109: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

# Store expressions that evaluate to True/Falsex = 1 < 2 # Truey = 5.0 == 4.0 # False

# Directly set to True/Falseis_sheltering = Trueis_raining = False

play_again = input(’Play again? "y” or "n”’) == ‘y’if play_again:

...

Boolean Variables

Page 110: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

*know your logical precedence

is_allowed = not food or drinks

Page 111: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

*know your logical precedence

is_allowed = not food or drinks

False

Page 112: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

*know your logical precedence

is_allowed = not food or drinks

False True

Page 113: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

ReviewConditions

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

Page 114: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

ReviewConditions

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

Page 115: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

How would you print “Python rocks socks”100 times

Page 116: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

public void run() :for i in range(100):

print(“Python rocks socks!”)

Page 117: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

i = 0while i < 100:

print(“Python rocks socks!”)i += 1

for i in range(100):print(“Python rocks socks!”)

Page 118: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(100):print(“Python rocks socks!”)

Create a countin

g

variable i

Which takes on the values 0 to 99 one at a time

Page 119: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

For Loop Redux

range(3) -> [0, 1, 2]

Page 120: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

For Loop Redux

range(3) -> [0, 1, 2]

Page 121: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 0

For Loop Redux

range(3) -> [0, 1, 2]

Page 122: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 0

For Loop Redux

Python rocks socks

range(3) -> [0, 1, 2]

Page 123: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 0

For Loop Redux

Python rocks socks

range(3) -> [0, 1, 2]

Page 124: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 1

For Loop Redux

Python rocks socks

range(3) -> [0, 1, 2]

Page 125: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 1

For Loop Redux

Python rocks socksPython rocks socks

range(3) -> [0, 1, 2]

Page 126: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3):print(“Python rocks socks!”)

i 1

For Loop Redux

Python rocks socksPython rocks socks

range(3) -> [0, 1, 2]

Page 127: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3): print(“Python rocks socks!”)

i 2

For Loop Redux

Python rocks socksPython rocks socks

range(3) -> [0, 1, 2]

Page 128: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3): print(“Python rocks socks!”)

i 2

For Loop Redux

Python rocks socksPython rocks socks

Python rocks socks

range(3) -> [0, 1, 2]

Page 129: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3): print(“Python rocks socks!”)

i 2

For Loop Redux

Python rocks socksPython rocks socks

Python rocks socks

range(3) -> [0, 1, 2]

Page 130: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

For Loop Redux

for i in range(3): print(“Python rocks socks!”)

i 3

For Loop Redux

Python rocks socksPython rocks socks

Python rocks socks

range(3) -> [0, 1, 2]

Page 131: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

You can use the for loop variable

Page 132: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

How would you print the first 100 even numbers?

Page 133: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

Page 134: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

For Loop Redux

Page 135: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

For Loop Redux

Page 136: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 0

For Loop Redux

Page 137: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 0

For Loop Redux

Page 138: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 0

For Loop Redux

0

Page 139: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 1

For Loop Redux

0

Page 140: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 1

For Loop Redux

0

2

Page 141: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 2

For Loop Redux

0

2

Page 142: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 2

For Loop Redux

0

2

4

Page 143: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 3

For Loop Redux

0

2

4

Page 144: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3):print(i * 2)

i 3

For Loop Redux

0

2

4

Page 145: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers

for i in range(3): print(i * 2)

For Loop Redux

0

2

4

Page 146: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Printing Even Numbers# our solutionfor i in range(3):

print(i * 2)

For Loop Redux

0

2

4

# equivalentlyfor i in range(0, 6, 2):

print(i)

Start at 0

Skip by 2 each

time

Stop before 6

0, 1, 2

Page 147: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Game Show

* To be delivered via amazon gift cards

Page 148: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Choose a Doordoor = int(input("Door: "))# while the input is invalidwhile door < 1 or door > 3 :

# tell the user the input was invalidprint("Invalid door!")# ask for a new inputdoor = int(input("Door: "))

orand

Page 149: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

prize = 4

if door == 1:prize = 2 + 9 // 10 * 100

elif door == 2:locked = prize % 2 != 0if not locked:

prize += 6

elif door == 3 :for i in range(door):

prize += i

The Door Logic

Page 150: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

That’s all

def main() :for i in range(999999):

print(“You rock!”)print(“See you on Monday”)

Page 151: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Route

ReviewConditions

For Loops

Booleans

Core Python

The Riv

er of Co

ntrol Flo

w

You are here

Page 152: Control Flow Revisited

Piech + Sahami, CS106A, Stanford University

Today’s Goal1. Be able to use For / While / If in Python