def main ():
input('press enter to begin testing...')
counter = 0
total = 0;
value = int( input ("Enter temp: or q to quit " ))
maxval = value
minval = value
while value:
counter += 1
total += value
if value > maxval:
maxval = value
if value < minval:
minval = value
value = int( input ("Enter temp: or q to quit "))
print ( 'Total is: ', total)
print ('Counter is: ', counter)
if counter != 0:
print ('Average is: ', total / counter)
print ('Minimum is: ', minval)
print ('Maximum is: ', maxval)
问题是当请求 temp
或 q
退出时,因为它是 int q
不被接受,因为它是 str .
我尝试提出单独的问题,但它无法正确计算循环。然后我尝试了 ord ('q')
,即 113
。我不确定如何成功申请或者是否有更好的方法。
最佳答案
您应该首先检查其内容,而不是将值直接转换为 int
:
value = input ("Enter temp: or q to quit ")
if value == 'q':
return
value = int(value)
关于python - 询问数字或字母时如何获得有效答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15443312/