请问以下代码有什么问题吗?
def add(x, y):
return x + y
while True:
try:
num1 = float(input('Enter first number: ')
except:
print ('num1 is a complex/string. Only Integers or Float is allowed. Please key in again')
try:
num2 = float(input("Enter first number: ")
except:
print ('num2 is a complex/string. Only Integers or Float is allowed. Please key in again')
break
print(num1,"+",num2,"=", add(num1,num2))
input("Press enter to exit ;)")
答案 0 :(得分:1)
(除了语法错误-缺少括号...)
break
语句转义了while循环,因此将其放在迭代结束时,您将在第一次迭代时中断,因此如果输入无效的输入,则不会再询问它们,因为你会爆发的。
此外,就只有一个循环而言,逻辑是错误的。如果他们输入有效的num1
,然后输入无效的num2
,则将要求他们(如果您移动break
)再次输入num1
和num2
-而不是再次num2
。
要解决这些问题,您可以对代码进行分隔-将输入逻辑移至函数:
def get_float(prompt):
while True:
try:
return float(input(prompt))
break
except ValueError:
print('sorry, invalid input')
然后您的主要代码更容易理解:
def add(x, y):
return x + y
num1 = get_float('Enter first number: ')
num2 = get_float('Enter second number: ')
result = add(num1, num2)
print(num1, '+', num2, '=', result)
input('press enter to exit')
试运行显示出良好的效果:
Enter first number: one
sorry, invalid input
Enter first number: bob
sorry, invalid input
Enter first number: 20
Enter second number: nine
sorry, invalid input
Enter second number: 8.89
20.0 + 8.89 = 28.89
press enter to exit
答案 1 :(得分:-1)
您需要使用raw_input仅接受输入提示。
def add(x, y):
return x + y
while True:
try:
num1 = float(raw_input('Enter first number: '))
except:
print ('num1 is a complex/string. Only Integers or Float is allowed. Please key in again')
try:
num2 = float(raw_input("Enter second number: "))
except:
print ('num2 is a complex/string. Only Integers or Float is allowed. Please key in again')
break
print(num1,"+",num2,"=", add(num1,num2))
raw_input("Press enter to exit ;)")