Skip to content

Instantly share code, notes, and snippets.

@joetechem
Last active March 2, 2017 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joetechem/99d51badbd674b0e3d60aefa7170694a to your computer and use it in GitHub Desktop.
Save joetechem/99d51badbd674b0e3d60aefa7170694a to your computer and use it in GitHub Desktop.
introducing while loops
# Python 2.7
# example code from Crash Course Python by Eric Matthes
# Recall for loops
# The for loop takes a collection of items and executes a block of code once
# for each item in the collection.
# PYTHON WHILE LOOPS
# In contrast, the while loop runs as longs as (or while) a certain condition is true
# For example, you can use a while loop to count up through a series of numbers.
# Let's say, we need a while loop that counts from 1 to 5:
current_number = 1 # we start counting from 1
while current_number <= 5:
print(current_number)
current_number += 1
# This loop is set to keep running as long as the value of current_number is
# less than or equal to 5.
# The code inside the loop prints the value of current_number and
# then adds 1 to that value with current_number += 1.
# (The += operator is shorthand for current_number = current_number + 1.)
# Python runs the loop as long as the condition ccurrent_number<= 5 is true.
# Because 1 is less than 5, Python prints 1 and then adds 1,
# making the current number 2, and so on.
# The loop stops when the value of current_number is greater than 5 and our program ends.
# While loops are used widely!
# The programs you use every day most likely contain while loops.
# For example, a game needs a while loop to keep running as long as you
# want to keep playing, so it can stop running when you want to quit.
# While loops are super useful!
####
####
# end_loop.py
# HOW TO STOP A LOOP
# Remember to write clear prompts!
prompt = ("\nTell me your name, and I will repeat it back to you:")
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = raw_input(prompt)
print(message)
# This program works well, except that it prints the word 'quit' as if it
# were an actual message.
# How can we fix this?
message = ""
while message != 'quit':
message = raw_input(prompt)
if message != 'quit':
print(message)
####
####
# again, consider a imple parrot program...
##prompt = ("\nTell me something, and I will repeat it back to you:")
##prompt += "\nEnter 'quit' to end the program. "
##
##message = ""
##while message != 'quit':
## message = raw_input(prompt)
## if message != 'quit':
## print(message)
# This program performs its task while a given condition is true.
# But, what about a more compplicated programs in which many different events
# could cause the program to stop running?
# Think of a game.
# Usually, several differentt events can end the game.
# i.e. when time runs out, when the player dies, when an enemy reaches a certain point, etc.
# If these examples occur, it can make the program end.
# If many possible events might occur to stop the program, just trying to test
# all these conditions in one while statement can become complicated and difficult!
###################
# Enter... FLAG
# For a program that should run only as long as many conditions are true, you
# can define one variable that determiens whether or not the entire the program is active.
# This variable, called a flag, acts as a signal to the program.
# We can run our programs so they run while the flag is set to True
# and stop running when any of several events sets the value of the flag to False
# so... SO, our overall while statement needs to check only one condition:
# whether or not the flag is currently True.
# This way, all our other tests can be neatly organized in the rest of the program.
# Alright, enough talking, let's add a flag to the parrot program!!!
prompt = ("\nTell me something, and I will repeat it back to you:")
prompt += "\nEnter 'quit' to end the program. "
active = True # starting our flag
while active:
message = raw_input(prompt)
if message != 'quit':
active = False # checking flag validity
else:
print(message)
# Python 2.7
# Example from Python Crash Course by Eric Matthes
# Using break to Exit a loop
# So far, we've looked at stopping a while loop by using a flag variable
# You can also use a BREAK statement...
# To exit a while loop immediately without running any remaining code in the loop,
# regardless of the results of any conditional test, use the break statement.
# The break statement directs the flow of your program
# You can use it to control which lines of code are executed and which aren't,
# so the program only executes code that you want it to, when you want it to
# Think of the term abstraction?
# Let's look at an example
# Consider a program that asks the user about places they've visited.
# To stop the while loop in this program by calling break as soon
# as the user enters the 'quit' value:
prompt = ("\nPlease enter the name of a city you have visited:")
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = raw_input(prompt)
if city == 'quit':
break
else:
print("I'd love to go " + city.title() + "!")
# this loop that starts with a "while True" will run continuously
# until it reaches a break statement
# You can use the break statement in any Python loops.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment