我正在尝试创建一个空列表,用户将填充随机整数,直到用户写'退出',然后程序应该计算整数的平均值(我应该这样做而没有来自Python模块或函数的帮助,如len()
)。我到目前为止我的代码:
# Start with an empty list.
numbers = []
# Set new_number to something other than 'exit'.
new_number = ''
# Start a loop that will run until the user enters 'exit'.
while new_number != 'exit':
new_number = int(input("Write a new number to the list, or enter 'exit': "))
# Add the new number to our list.
if new_number != 'exit':
numbers.append(new_number)
# Start calculating the mean of the numbers.
def average(numbers):
total = 0
count = 0
for num in numbers:
total += num
count += 1
return total / count
Numbmean = average(numbers)
print( 'The mean: ' + round(Numbmean ,2))
但是,我会遇到以下两种情况:
程序不喜欢我试图将'exit'指定为整数,(ValueError: invalid literal for int() with base 10: 'exit'
)或:
程序无法计算字符串变量的均值,因为输入将成为字符串(TypeError: unsupported operand type(s) for +=: 'int' and 'str'
)。
我该如何解决这个问题?
答案 0 :(得分:0)
第一个问题是由以下行引起的:
new_number = int(input("Write a new number to the list, or enter 'exit': "))
如果用户键入exit
,则输入将返回它,并且自然不能将其转换为导致ValueError
的整数。您可以通过首先检查input
返回值是否与exit
匹配来解决此问题,如果确实如此,则打破循环。检查后,您可以将返回值转换为int并将其附加到列表中。
# Start a loop that will run until the user enters 'exit'.
while True:
new_number = input("Write a new number to the list, or enter 'exit': ")
# Add the new number to our list.
if new_number == 'exit':
break
try:
numbers.append(int(new_number))
except ValueError:
print('Please enter number or exit')
这也应该解决您遇到的第二个错误,因为它确保numbers
中的所有项都是整数。