Repetition Based on User Input
We can use function input in a loop to make the chemical formula translation example from Choosing Which Statements to Execute, interactive. We will ask the user to enter a chemical formula, and our program, which is saved in a file named formulas.py, will print its name. This 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 ...
Get Practical Programming, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.