September 2013
Intermediate to advanced
350 pages
9h 38m
English
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 ...
Read now
Unlock full access