我想保护我创建的python计算器在用户输入字符串而不是整数时崩溃。
我曾尝试使用else语句打印“无效输入”(或其他我无法记住的事情),当用户输入字符串而不是数字时。
我还想知道是否有办法让用户执行其他操作,而不必重新启动应用程序。
如果需要进行任何导入(如果可以),请列出它是否与cx_Freeze兼容。
源代码:
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("Invalid input")
答案 0 :(得分:7)
您可以使用类似的内容输入
while True:
try:
num1 = int(input("Enter first number: "))
except ValueError:
continue
else:
break
答案 1 :(得分:2)
请查看我对您的代码所做的更改,如下所示:
def add (x, y):
return(x + y)
def subtract(x, y):
return(x - y)
def multiply(x, y):
return(x * y)
def divide(x, y):
return(x / y)
def input_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That was not a number")
# Keep going around the loop until the user chooses 5 to quit
while True:
print
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Quit")
choice = input("Enter choice(1/2/3/4/5):")
# Do they want to quit?
if choice == 5:
break
num1 = input_number("Enter first number: ")
num2 = input_number("Enter second number: ")
if choice == 1:
print(num1,"+",num2,"=", add(num1,num2))
elif choice == 2:
print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == 3:
print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == 4:
print(num1,"/",num2,"=", divide(num1,num2))
else:
print("%s - Invalid input" % choice)
为了要求更多输入,您需要将提示包装在一个循环中。然后,您需要向用户添加一个选项以允许它们退出。
此外,您可以将数字提示移动到某个功能。如果用户键入了一个字符,这将继续询问号码。
答案 2 :(得分:0)
此代码段应该有用: -
def is_string(test_data):
if type(test_data) is str:
return True
else:
return False