Converting to a while loop
You can often achieve the same tasks using either a for
or while
loop.
To demonstrate this, you'll convert this for
loop into a while
!
# Create the tickets_sold variable
tickets_sold = 0
# Create the max_capacity variable
max_capacity = 10
# Loop through a range up to and including max_capacity's value
for tickets in range(1, max_capacity + 1):
# Add one to tickets_sold in each iteration
tickets_sold += 1
print("Sold out:", tickets_sold, "tickets sold!")
Note that if your while
loop takes too long to run, or your session is expiring, you might have created an infinite loop. In particular, remember to indent the contents of the loop using four spaces or auto-indentation, and make sure the conditions are such that the loop has a stopping point.
This exercise is part of the course
Introduction to Python for Developers
Exercise instructions
- Create a while loop to run while
tickets_sold
is less thanmax_capacity
. - Inside the loop, increment
tickets_sold
by 1, representing an increase for each ticket sold. - Outside of the loop, print
tickets_sold
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
tickets_sold = 0
max_capacity = 10
# Create a while loop
____ ____ ____ ____:
# Add one to tickets_sold in each iteration
tickets_sold += ____
# Print the number of tickets sold
print("Sold out:", ____, "tickets sold!")