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 of text, we have to assign it a value before the loop begins. Now we 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 execute at least once.