Go to Chapter 51 of A Smarter Way.
Recall for loops:
http://localhost/2018/10/02/python-for-loops/
for friend in friends: print("Hello, " + friend.title() + "!")
For loops are good for meeting a single condition, once. But sometimes you need to keep performing the matching operation. This is where while loops are more useful.
# A list to test against my_cats = ["Betty", "Ginger", "Nico", "Sven", "Hudson"] # If you're going to be accepting repeat input, #you'll need to initialize a variable# as an empty value.user_input = ""while user_input != "q": user_input = input("Enter a cat name, or q to quit: ") if user_input != "q": for one_cat in my_cats: if user_input == one_cat: print(one_cat + " is one of my cats") break
Indent carefully!
Go to Chapter 51 of A Smarter Way.
Setting a Flag to Continue or End Looping
# Set a flag to control looping keep_looping = True while keep_looping == True: user_input = input("Enter a cat name, or q to quit: ") if user_input != "q": for one_cat in my_cats: if user_input == one_cat: print(one_cat + " is one of my cats") break else: keep_looping = False
This is a useful place to use a file to supply input. See this example from
http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/:
# Open the file read-only f = open('input_file.txt') # use readline() to read the first line line = f.readline() # If the file is not empty keep reading one line # at a time, till the file is empty while line: # In python 2+ use the syntax: # print line # In python 3 print is a builtin function, # So use this syntax: print(line) # Then use realine() to read next line line = f.readline() f.close()
The article linked above provides more examples that handle the input file differently. Read it.