我已經創建了這個計算器,但是現在我想通過創建一個錯誤消息「請只輸入數字」來改進它。但我在哪裏添加?創建我自己的錯誤信息?但是哪裏?
這是我的代碼:
def menu():
print "Welcome to the calculator"
print "The options are 1) Addition 2)Subtraction 3)Multiplication 4)Division 5)Exit Calculator"
return input("Choose your option")
def add(a,b):
print a+b
def sub(a,b):
print a-b
def mult(a,b):
print a*b
def div(a,b):
print a/b
loop=1
choice=0
while loop==1:
choice=menu()
if choice==1:
add(input("Enter first number"),input("Enter second number"))
elif choice==2:
sub(input("Enter first number"),input("Enter second number"))
elif choice==3:
mult(input("Enter first number"),input("Enter second number"))
elif choice==4:
div(input("Enter first number"),input("Enter second number"))
elif choice==5:
loop=0
exit()
感謝:-)
這是有道理的,但是我不能讓它工作?我不知道爲什麼。 當我測試它時,它仍然會出現消息「q(或任何我輸入的字母」未定義「) 非常感謝 – user3105095
@ user3105095您在進行類型檢查之前是否忘記了指定給'q'?答案的第二行:'a = input(「輸入第一個數字:」)' –
您還應該考慮使用'isinstance(a,numbers.Number)'(在導入['numbers']之後(http:// docs.python.org/3.3/library/numbers.html))而不是'type(a)!= int和type(a)!= float'。使用'isinstance'意味着你的代碼可以處理任何類型的數字,包括複數:) –