0% found this document useful (0 votes)
2 views

While_if in Python

The document discusses the use of variables, loops, and conditional statements in Python programming. It includes examples of creating and modifying variables, using arithmetic operators, and implementing while and if statements. Additionally, it features a practical example of calculating distance based on Usain Bolt's speed.

Uploaded by

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

While_if in Python

The document discusses the use of variables, loops, and conditional statements in Python programming. It includes examples of creating and modifying variables, using arithmetic operators, and implementing while and if statements. Additionally, it features a practical example of calculating distance based on Usain Bolt's speed.

Uploaded by

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

While/If Revisited

Chris Piech and Mehran Sahami


Stanford University
Review
Variables are like Boxes

num_students = 700

num_students 700
700

name
value
Variables are like Boxes

num_students = 700

int
num_students 700
700

name type
value
Teeny Tiny Boxes

My computer has space for


about 10 billion boxes
Create, Modify, Use
# Create a variable, of type int
# called age.
age = 37

# Use the value in age (output it)


print(f"age is: {age}")

# Modify age to be one greater.


age = age + 1
Create, Modify, Use
# Create a variable, of type int
# called age.
age = 37

# Use the value in age (output it)


print(f"age is: {age}")

# Modify age to be one greater.


age = age + 1
Arithmetic Operators
+ Addition * Multiplication
- Subtraction / Division
Review Example: Bolt Calculator
Usain Bolt has the
record speed for
any human

He was recorded
going 10.44 meters
per second
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Run time (s):
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Run time (s):
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
Run time (s): 60
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal
% python main.py
str
"60"
Run time (s): 60
time_str
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
time_str time
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
time_str time
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
time_str time
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
time_str time

float
626.4
distance
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
time_str time

float
626.4
distance
Review: Bolt Calculator
SPEED = 10.44 # Bolt's speed in meters / second

def main():
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")

terminal

float
% python main.py
str
"60" 60.0
Run time (s): 60
Bolt can run 626.4 meters time_str time

float
626.4
distance
End Review
Today’s Goal
1. Be able to use For / While / If in Python
Today’s Route
You are here
Core
Python

While/If
Review
Today’s Route
You are here
Core
Python

While/If
Review
While Loop in Karel

while front_is_clear() :
body

if beepers_present() :
body
While Loop Redux

while condition : if condition :


body body

The condition should be a boolean which is


either True or False
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
While Loop: Bolt Distance

SPEED = 10.44 # Bolt's speed in meters / second

def main():
while True: while True:
time_str = input("Run time (s): ")
time = float(time_str)
distance = SPEED * time
print(f"Bolt can run {distance} meters.")
Today’s Route
You are here
Core
Python

While/If
Review
Today’s Route
You are here
Core
Python

While/If
Review
Booleans

front_is_clear()

True
Booleans

beepers_present()

True
Booleans

s = "123"
s.is_digit()

True
Booleans

my_var < 3

True
Comparison Operators

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

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
Spot the difference #1

x = 7 x == 7

Sets the value of a Checks if a variable


variable named x to be named x has the
7. Creates the variable value 7
if it didn't exist.
Spot the difference #2

x == 5 x == "5"

Checks if x is the Checks if x is the


number 5 string 5
Comparison Operators
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.")
If Else Revisited

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

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

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

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

Enter a number: 5
If Else Revisited
5 “5”
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")

Enter a number: 5
If Else Revisited
5
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")

Enter a number: 5 5
num
If Else Revisited

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

Enter a number: 5 5
num
If Else Revisited

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

Enter a number: 5 5
num
If Else Revisited

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

Enter a number: 5 5
Your number is positive
num
If Else Revisited

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

Enter a number: 5 5
Your number is positive
num
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
Amazing
Guess My Number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
50
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
50
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
50
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
50
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
50
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
95
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
92
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
92
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
92
int

guess secret_number
Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")

92

int
92
int

guess secret_number
Behind the Scenes-
Guess My Number
secret_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 number
while ???:
# Report on the old guess
# Get a new guess

print(f"Congrats! The number was: {secret_number}")

92

int
secret_number
Guess My Number
secret_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 number
while ???:
# Repeat some stuff???

print(f"Congrats! The number was: {secret_number}")


Guess My Number
secret_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 number
while ???:
# Get a new guess

# Report high/low

print(f"Congrats! The number was: {secret_number}")


Guess My Number
secret_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 number
while ???:
# Get a new guess
guess = int(input("Enter a guess: "))

# Report high/low

print(f"Congrats! The number was: {secret_number}")


Guess My Number
secret_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 number
while guess != secret_number:
# Get a new guess
guess = int(input("Enter a guess: "))

# Report high/low

print(f"Congrats! The number was: {secret_number}")


Guess My Number
secret_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 number
while guess != secret_number:
# Report high/low

# Get a new guess


guess = int(input("Enter a guess: "))

print(f"Congrats! The number was: {secret_number}")


Guess My Number
secret_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 number
while guess != secret_number:
# True if guess is less than secret number
if guess < secret_number:
print("Your guess is too low")
else:
print("Your guess is too high")

print("") # an empty line


guess = int(input("Enter a new guess: "))

print(f"Congrats! The number was: {secret_number}")


George Boole

English Mathematician teaching in Ireland 1815 – 1864


Boole died of being too cool
Logical Operators
In order of precedence:
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
Boolean Variables

# Store expressions that evaluate to True/False


x = 1 < 2 # True
y = 5.0 == 4.0 # False

# Directly set to True/False


is_sheltering = True
is_raining = False

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


if play_again:
...
Today’s Route
You are here
Core
Python

Conditions
Review

You might also like