Python Error (simple) (am I Going Crazy?)
Solution 1:
In Python, you can add strings but cannot subtract them. input()
gives you a string. "hello "+"world"
will result in "hello world"
, but "hello "-"world"
will give you an error. You can also multiply string, but only by a number (an integer) like this: "a"*3=="aaa"
.
Here you want inputed data be a number. Use int()
or float()
then.
Solution 2:
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:
defmenu():
menu = ['+ [1]', '- [2]', '/ [3]', '* [4]', 'Exit [0]']
print(menu)
whileTrue:
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")
returnelse:
print("Invalid choice")
defadd():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a +b)
defsub():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a -b)
defdiv():
a = int(input("Number 1: "))
b = int(input("Number 2: "))
print(a / b)
defmult():
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
defget_nums():
whileTrue:
try:
a = float(input("Number 1: "))
b = float(input("Number 2: "))
return a,b
except ValueError:
print("Not a valid number")
defmenu():
menu = ['+ [1]', '- [2]', '/ [3]', '* [4]', 'Exit [0]']
print(menu)
ops = {"1":add,"2":sub,"3":truediv,"4":mul}
whileTrue:
x = input("Choose and option 0-4: ")
if x == '0':
print("Terminating")
returnif x in ops:
a,b = get_nums()
print(ops[x](a,b))
else:
print("Invalid choice")
Post a Comment for "Python Error (simple) (am I Going Crazy?)"