[英]Asks user to input floating-point values. If invalid inputs more than twice, quit the program using python
I have to make a function that requests non-zero floating-point values from the user; 我必须创建一个函数,要求用户提供非零浮点值。 when the user enters 0, the sum of the numbers input is printed.
当用户输入0时,将打印输入的数字总和。 The function terminates when the user enters two invalid inputs in a row.
当用户连续输入两个无效输入时,该函数终止。
I have the following code: 我有以下代码:
def inValues():
counter = 0
s = 0
while True:
if counter <= 2:
try:
digit = input('Please enter a number: ')
counter += 1
floatDig = float(digit)
break
else:
break
except:
print('Error. Please re-enter the value.')
if floatDig == 0:
s += sum(floatDig)
return s
But when ran, it asks for one input only, then stops. 但是运行时,它仅要求一个输入,然后停止。 I'm pretty sure the code is pretty scrambled and broken so any help is appreciated.
我很确定代码已经被打乱和破坏了,因此可以提供任何帮助。
Few notes: 一些注意事项:
while
loop can have a condition - so I use it for the error counting while
循环可以有条件-因此我将其用于错误计数 break
exits the while
loop - so I removed it (we now use it for monitoring error count). break
退出while
循环-因此我将其删除(我们现在将其用于监视错误计数)。 Code: 码:
def inValues():
errorcounter = 0
s = 0
while errorcounter < 2: # errorcounter = [0, 1] ...
digit = input('Please enter a number: ')
if digit == '0':
# return sum of numbers
return s
try:
# try and summarize input
s += float(digit)
except:
print('Error. Please re-enter the value.')
errorcounter += 1
print("Too many errors.")
# possibly return indicative value (None?)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.