Книга: Practical Programming, Fourth Edition
Назад: Looping Until a Condition Is Reache d
Дальше: Controlling Loops Using break and continue

Repetition Based on User Input

You can use function input in a loop to make the chemical formula translation example from , interactive. You will ask the user to enter a chemical formula, and your program, which is saved in a file named formulas.py, will print its name. The loop should continue until the user types quit:

 text = ​""
 while​ text != ​"quit"​:
  text = input(​"Please enter a chemical formula (or 'quit' to exit): "​)
 if​ text == ​"quit"​:
 print​(​"…exiting program"​)
 elif​ text == ​"H2O"​:
 print​(​"Water"​)
 elif​ text == ​"NH3"​:
 print​(​"Ammonia"​)
 elif​ text == ​"CH4"​:
 print​(​"Methane"​)
 else​:
 print​(​"Unknown compound"​)

Since the loop condition checks the value of the text, you must assign it a value before the loop begins. Now, you can run the program in formulas.py, and it will exit whenever the user types quit:

 Please enter a chemical formula (or 'quit' to exit): ​CH4
 Methane
 Please enter a chemical formula (or 'quit' to exit): ​H2O
 Water
 Please enter a chemical formula (or 'quit' to exit): ​quit
 …exiting program

The number of times that this loop executes will vary depending on user input, but it will iterate at least once.

Назад: Looping Until a Condition Is Reache d
Дальше: Controlling Loops Using break and continue