calculation =input("> ")parts = calculation.split() # Split e.g. "4 * 6" into ["4", "*", "6"]lhs =int(parts[0]) # Extract e.g. "4" and turn it into 4operation = parts[1] # Extract e.g. "*"rhs =int(parts[2]) # Extract e.g. "6" and turn it into 6if operation =="+":print(calculation, "is", lhs + rhs)elif operation =="-":print(calculation, "is", lhs - rhs)elif operation =="*":print(calculation, "is", lhs * rhs)elif operation =="/":print(calculation, "is", lhs / rhs)
Terminal/Command Prompt
python calc.py
> 4 * 6
4 * 6 is 24
> 5 + 6
5 + 6 is 11
> 457 - 75
457 - 75 is 382
> 54 / 3
54 / 3 is 18.0
The code above works fine, but there’s always more than one way to approach a problem like this.
Separating calculation from output
One thing that we could improve would be the repetition in the print lines. Each of them are almost the same as each other and if we wanted to change the output from
4 * 6 is 24
to something like
4 * 6 = 24
then we’d have to edit all four lines of code.
Remembering our three-part pattern from earlier in the course of input→calculation→output, it’s a good idea to split out the calculation of data from the printing and display of data. In our case we could change it to look like:
calc.py
calculation =input("> ")# Prepare the partsparts = calculation.split()lhs =int(parts[0])operation = parts[1]rhs =int(parts[2])# Calculate the answerif operation =="+": result = lhs + rhselif operation =="-": result = lhs - rhselif operation =="*": result = lhs * rhselif operation =="/": result = lhs / rhs# Output the resultprint(calculation, "is", result)