input is a string, you need to cast each one before you try to do addition etc.. :
a = int(input("Number 1: "))
b = int(input("Number 2: "))
If you are worried about the user entering extra whitespace when comparing the first user input use str.strip
:
x = input("Choose and option 0-4: ").strip()
If you use x = input("Choose and option 0-4: ")[:1]
and the user enters a space followed by a 1 " 1"
you will get an empty string as the value where strip will just remove the whitespace.
You only need cast in the functions you are doing math operations. It is fine to just compare x
to "1"
etc..
You can use a while loop to verify the initial user input:
def menu():
menu = ['+ [1]', '- [2]', '/ [3]', '* [4]', 'Exit [0]']
print(menu)
while True:
x = input("Choose and option 0-4: ")[:1]
if x == '1':
add()
elif x == '2':
sub()
elif x == '3':
div()
elif x == '4':
mult()
elif x == '0':
print("Terminating")
return
else:
print("Invalid choice")
def add():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a +b)
def sub():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a -b)
def div():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a / b)
def mult():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a * b)
But using a dict the operator module and one helper function would be much better:
from operator import add, truediv, sub, mul
def get_nums():
while True:
try:
a = float(input("Number 1: "))
b = float(input("Number 2: "))
return a,b
except ValueError:
print("Not a valid number")
def menu():
menu = ['+ [1]', '- [2]', '/ [3]', '* [4]', 'Exit [0]']
print(menu)
ops = {"1":add,"2":sub,"3":truediv,"4":mul}
while True:
x = input("Choose and option 0-4: ")
if x == '0':
print("Terminating")
return
if x in ops:
a,b = get_nums()
print(ops[x](a,b))
else:
print("Invalid choice")