Make me look good. Click on the cell below and press Ctrl+Enter.
from IPython.core.display import HTML
HTML(open('css/custom.css', 'r').read())
while
loopsOften you will want to get information from a user and incorporate that information into your program.
In Python, we can use the input()
function to do this.
Pro tip. The input()
function always results in the user input being converted to a string.
Consider the following example:
# Ask for the user's age
age = input("What is your age? ")
# What type of data does input() return?
print(type(age))
What is your age? 27 <class 'str'>
int()
and float()
respectively:# Convert age to an integer
age_int = int(age)
# Print to check the new variable
print(age_int)
# What type does the new variable have?
print(type(age_int))
27 <class 'int'>
# Covert age to a float
age_float = float(age)
# Print to check the new variable
print(age_float)
# What type does the new variable have?
print(type(age_float))
27.0 <class 'float'>
Problem. (PCC 5-10: Checking Usernames, modified) Do the following to create a program that simulates how websites ensure that everyone has a unique username.
current_users
.Nelson
and nelson
are not the same).# List of current users
current_users = ['ProfessorAwesome', 'Bingham', 'RustyChipmunk', 'ShineSpike', 'IAmSam15']
# Ask user to input desired username
username = input("Please enter a username: ")
# Check if user's desired username is taken
if username in current_users:
print("I'm sorry, that username is taken.")
else:
print("Congratulations, that username is available!")
Please enter a username: ProfessorAwesome I'm sorry, that username is taken.
A while
loop runs a block of code while some statement is true.
A while
loop stops only when the statement evaluates to False
, or when the break
statement is used
Consider the following examples:
from IPython.display import IFrame
IFrame("http://pythontutor.com/iframe-embed.html#code=x%20%3D%200%0Awhile%20x%20%3C%3D%205%3A%0A%20%20%20%20print%28x%29%0A%20%20%20%20x%20%2B%3D%201&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false", width=800, height=400)
from IPython.display import IFrame
IFrame("http://pythontutor.com/iframe-embed.html#code=x%20%3D%200%0Awhile%20True%3A%0A%20%20%20%20print%28x%29%0A%20%20%20%20x%20%2B%3D%201%0A%20%20%20%20%0A%20%20%20%20if%20x%20%3E%205%3A%0A%20%20%20%20%20%20%20%20break%0A%20%20%20%20&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false", width=800, height=400)
for
loops always run for a fixed number of iterations.
On the other hand, it is possible for a while
loop to run forever!
The code cell below contains an example of an infinite loop.
To stop the code in the cell below, you will need to click on the ◼ button (interrupt the kernel) or the ↻ button (restart the kernel) in the toolbar.
x = 0
while True:
print(x)
x += 1
Problem. (PCC 5-10: Checking Usernames, modified again) Do the following to create a program that simulates how websites ensure that everyone has a unique username.
current_users
.Nelson
and nelson
are not the same).# List of current users
current_users = ['ProfessorAwesome', 'Bingham', 'RustyChipmunk', 'ShineSpike', 'IAmSam15']
# Ask user to input desired username
while True:
username = input("Please enter a username: ")
# Check if user's desired username is taken
# If it isn't, stop the while loop
if username in current_users:
print("I'm sorry, that username is taken.")
else:
print("Congratulations, that username is available!")
break
Please enter a username: ProfessorAwesome I'm sorry, that username is taken. Please enter a username: ProfessorBoring Congratulations, that username is available!
A flag is a variable that acts as a symbol to either stop a program or exit a loop.
Usually a flag variable is either True
or False
.
Let's use a flag and a while loop to simulate the precarious position Robin Williams found himself in during the movie Jumanji. In the movie, the following rule had to be observed:
In the jungle, you must wait, until the dice read five or eight.
# Below we import the randint function from the random library
# so that we can "roll" the dice in the code below
from random import randint
# Create a flag representing whether we're in the jungle
# Initialize flag to True
in_jungle = True
while in_jungle:
# Simulate the roll of 2 dice
die1 = randint(1, 6)
die2 = randint(1, 6)
# Get the total
dice_roll = die1 + die2
print(dice_roll)
# If the total is 5 or 8, update the flag to False
if dice_roll == 5 or dice_roll == 8:
in_jungle = False
6 4 5
Problem 1. (PCC 7-1: Rental Car) Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as
Let me see if I can find you a Subaru.
# Ask user for car type
car = input("What kind of car would you like? ")
# Print message with user input
print(f"Let me see if I can find you a {car}.")
What kind of car would you like? DeLorean Let me see if I can find you a DeLorean.
Problem 2. (PCC 7-3: Multiples of Ten) Ask the user for a number, and then report whether the number is a multiple of 10 or not.
# Ask user for number
number = input("Please enter a number: ")
# Check if the number is a multiple of 10
if (int(number) % 10) == 0:
print("That is a multiple of ten!")
else:
print("That is not a multiple of ten!")
Please enter a number: 792 That is not a multiple of ten!
Problem 3. Write code that asks for 2 numbers from the user and sets the variable total
equal to their sum. Print the value of total
.
# Ask the user for two numbers
first_num = input("Enter the first number: ")
second_num = input("Enter the second number: ")
# Convert the user input from strings to floats
first_num = float(first_num)
second_num = float(second_num)
# Add the numbers
total = first_num + second_num
# Print the total value
print(f"The sum of your two numbers is {total}.")
Enter the first number: 42 Enter the second number: 36 The sum of your two numbers is 78.0.
Problem 4 (PCC 7-5: Movie Tickets). A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is \$10; and if they are over age 12, the ticket is \$15. Write a loop in which you repeatedly ask users their age, and then tell them the cost of their movie ticket.
while True: # loops forever but you get an error if you enter text
age = input("What is your age? ")
if int(age) < 3:
message = "Your ticket is free!"
elif int(age) <= 12:
message = "Your ticket costs $10."
else:
message = "Your ticket costs $15"
print(message)
What is your age? 78 Your ticket costs $15 What is your age? 32 Your ticket costs $15 What is your age? oops
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-13-5de926418892> in <module>() 1 while True: # loops forever but you get an error if you enter text 2 age = input("What is your age? ") ----> 3 if int(age) < 3: 4 message = "Your ticket is free!" 5 elif int(age) <= 12: ValueError: invalid literal for int() with base 10: 'oops'
Problem 5. Take a quick break.
Problem 6. (PCC 7-6: Three Exits) Read pages 118-123 of PCC on while
loops and make sure you understand the different ways of stopping a while
loop.
Write different versions of Problem 4 that do each of the following:
q
.q
.q
.# Conditional exit
age = 0
while age != 'q':
age = input("What is your age? (enter q to quit) ")
if age == 'q':
message = "See you soon!"
elif int(age) < 3:
message = "Your ticket is free!"
elif int(age) <= 12:
message = "Your ticket costs $10."
else:
message = "Your ticket costs $15"
print(message)
What is your age? (enter q to quit) 1 Your ticket is free! What is your age? (enter q to quit) 10 Your ticket costs $10. What is your age? (enter q to quit) q See you soon!
# Flag exit
active = True
while active:
age = input("What is your age? (enter q to quit) ")
if age == 'q':
active = False
message = "See you soon!"
elif int(age) < 3:
message = "Your ticket is free!"
elif int(age) <= 12:
message = "Your ticket costs $10."
else:
message = "Your ticket costs $15"
print(message)
What is your age? (enter q to quit) 1 Your ticket is free! What is your age? (enter q to quit) 10 Your ticket costs $10. What is your age? (enter q to quit) q See you soon!
# Break exit
while True:
age = input("What is your age? (enter q to quit) ")
if age == 'q':
print("See you soon!")
break
if int(age) < 3:
message = "Your ticket is free!"
elif int(age) <= 12:
message = "Your ticket costs $10."
else:
message = "Your ticket costs $15"
print(message)
What is your age? (enter q to quit) 1 Your ticket is free! What is your age? (enter q to quit) 10 Your ticket costs $10. What is your age? (enter q to quit) q See you soon!
Problem 7. Use a while loop to approximate $\sum_{k=1}^{\infty} \frac{1}{k^3}$ by summing all terms whose value is greater than $10^{-6}.$ Print your approximation.
# Initialize total value
# Don't call the variable sum, which is a function name
total = 0
# Keep going while 1 / k^3 is greater than 10^-6
k = 1
while 1 / k**3 > 1e-6:
total += 1 / k**3
k += 1
# Print the approximation
print(f"The sum of 1/k^3 for all k >= 1 is approximately {total}.")
The sum of 1/k^3 for all k >= 1 is approximately 1.2020064006596782.
Problem 8. Add up the squares from $1^2$ to $1000^2$ by
sum
function.Print your answer. (This doesn't use material from this lesson; this is just a warm up for the next problem.)
# Create list of squares using a list comprehension
values = [i**2 for i in range(1, 1001)]
# Add the squares, print the total
print(f"The sum of the first 1000 squares is {sum(values)}.")
The sum of the first 1000 squares is 333833500.
Problem 9. Use a while
loop to add the squares from $1^2$ to $1000^2$. Print your answer. Hopefully you get the same answer as you did in Problem !
# Variable to hold total value
# Don't call the variable sum, which is a function name
total = 0
# Start with 1^2, and keep on going until we reach 1000^2
i = 1
while i <= 1000:
total += i**2
i += 1
# Print the total
print(f"The sum of the first 1000 squares is {total}.")
The sum of the first 1000 squares is 333833500.
Problem 10. What does the following code do? Run this code. Then run it with other positive integers instead of 17. What do you think happens in general? You've just made a conjecture. Compare it with the Collatz conjecture (search on the internet for this term).
number = 17
print(number)
while number != 1:
if (number % 2)==0:
number = int(number / 2)
else:
number = 3 * number + 1
print(number)
17 52 26 13 40 20 10 5 16 8 4 2 1
Write your notes here. Double-click to edit.
The code repeatedly divides an even number by 2 and multiplies an odd number by 3 and adds 1. It does this until the number reaches 1. I predict that this process will reach 1 no matter our choice of starting number. This is called the Collatz conjecture.