Solution: Calculator
Here I used the format method of the strings to insert the value of op in the {} placeholder. We'll learn about this later on.
examples/basics/calculator.py
def main(): a = float(input("Number: ")) b = float(input("Number: ")) op = input("Operator (+-*/): ") if op == '+': res = a+b elif op == '-': res = a-b elif op == '*': res = a*b elif op == '/': res = a/b else: print(f"Invalid operator: '{op}'") return print(res) return main()
- For historical reasons we also have the solution in Python 2
examples/basics/calculator_python2.py
from __future__ import print_function a = float(raw_input("Number: ")) b = float(raw_input("Number: ")) op = raw_input("Operator (+-*/): ") if op == '+': res = a+b elif op == '-': res = a-b elif op == '*': res = a*b elif op == '/': res = a/b else: print("Invalid operator: '{}'".format(op)) exit() print(res)