对于我的作业,我必须创建一个程序,让用户输入多个数字。我还想创建一个包含所有数字及其平均值的列表。
但是如何为数字列表创建代码?
我应该以0或-999之类的数字退出。
一行语法无效。
print (number_list[i], end = " ")
这是我的代码。
number_list = []
sum = 0.0
user_number = eval(input("Please enter a number (-999 quits): "))
# Loop until the user is ready to quit
while (user_number != -999):
number_list.append(user_number)
sum = sum + user_number
user_number = eval(input("Please enter a number (-999 quits): "))
# Make sure the user entered something
if (len(number_list) != 0):
# Compute average
average = sum / len(number_list)
# Do output
print ("Using the numbers:")
for i in range(len(number_list)):
# Note the end = " " at the end will keep the output on
# the same line
print (number_list[i], end = " ")
# Note the \n at the start of this line is needed because
# the previous print statement ended with a comma. This
# \n will move the cursor to the next line
print ("\nThe average is:", average)
else:
print ("No values were entered")
答案 0 :(得分:1)
由于Python的缩进规则,任何复合语句都必须在其后至少缩进一条语句。
让我们关注代码的这一部分:
for i in range(len(number_list)):
print (number_list[i], end = " ")
print ("\nThe average is:", average)
else:
print ("No values were entered")
for
循环是一个复合语句,因为它需要缩进的内容。您需要相应地缩进。像这样:
for i in range(len(eggs)):
print(eggs[i])
遍历内容的pythonic方法是使用值而不是获取索引然后找到它。 Python的for
循环比实际的foreach
循环更像for
循环。重新制作看起来像:
for spam in eggs:
print(spam)
此外,您还要检查是否没有数字。为此,请使用普通的if
语句,而不是循环中的一个。当主体部分(else
或while
)完成而没有for
时,循环后面的break
将运行。
此:
for spam in eggs:
print(spam)
else:
print("Nothing")
与此不同:
if eggs:
for spam in eggs:
print(spam)
else:
print("Nothing")
这是固定部分:D
# If statement to check if list is truthy (nonempty)
if number_list:
# Note the for loop's target 'number'
for number in number_list:
# Note indentation.
print(number, end=" ")
print("\nThe average is:", average)
else:
print("No values were entered")
编辑:在本节上方的while
循环之后,您也有缩进错误。我会留给您修复:)