硬件帮助循环和错误预期以及"完成"



条件为:重复读取数字,直到用户输入"完成"。一旦输入"done",就跳出循环。如果用户输入除数字以外的任何内容,则使用try-except结构捕获错误并显示消息";"坏数据";输入"完成"后,打印出以下两条消息之一:如果总数大于或等于200,则:"输入的数字的总和(总变量中的值(是"大";如果总数小于200,则:"输入的数字的总和(总变量中的值(是"小";

count = 0
while count <= 200:
x = int(input('Please enter a number to add: '))
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break
elif x == 'done':
print ('The total',count,'for the number entered is Small')
break
elif x == ValueError:
print('Bad Data')
continue

我是一个初学者,所以给我一点帮助会很酷。

当您接受输入值时,在尝试将其转换为int之前,您需要检查它是否是一个数字。因此,有两种方法可以做到这一点:要么将第一行包装在try-except块中以捕捉值错误,要么只检查它们提供的输入是否真的是一个数值。正如Tim Roberts在上面所说;完成";如果您已经转换为整数,那么这就是为什么我将该复选框移到每个示例的顶部。

版本1(尝试除外(:

count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
try:
x = int(user_input)
except ValueError:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break

版本2(检查编号(:

count = 0
while count <= 200:
user_input = input('Please enter a number to add: ')
if user_input.lower() == 'done':
print('The total', count, 'for the number entered is Small')
break
if user_input.isnumeric():
x = int(user_input)
else:
print('Bad Data')
continue
count = count + x
if x >= 200:
print('The total', count, 'for the number entered is Large')
break

PS。将.lower((添加到user_input允许他们键入"done"或"done"或大写和小写的任何组合,并且它仍然会退出。

我已经对您的代码进行了一些编辑。这可能有助于你理解其中的逻辑。

total = 0
while True:
userInput = input('Please enter a number to add: ')
if userInput == "done":
break
try:
x = int(userInput)
total += x
if total >= 200:
print('The total', total, 'for the number entered is Large')
elif total <=  200:
print ('The total',total,'for the number entered is Small')
except:
print("Bad Data")

几点注意事项。我已经将count的名称更改为total,因为您的问题的逻辑似乎更接近这个名称。

输出

Please enter a number to add: I am inputting bad data
Bad Data
Please enter a number to add: 100
The total 100 for the number entered is Small
Please enter a number to add: 0
The total 100 for the number entered is Small
Please enter a number to add: 50
The total 150 for the number entered is Small
Please enter a number to add: 30
The total 180 for the number entered is Small
Please enter a number to add: -50
The total 130 for the number entered is Small
Please enter a number to add: done

相关内容

最新更新