我正在用 python 处理这个任务,但我不确定我是否以正确的方式将元素添加到列表中。所以基本上我假设创建一个 create_list 函数,它获取列表的大小并提示用户输入那么多值并将每个值存储到列表中。 create_list 函数应该返回这个新创建的列表。最后,main() 函数应提示用户输入值的数量,将该值传递给 create_list 函数以设置列表,然后调用 get_total 函数打印列表的总数。请告诉我我遗漏了什么或做错了什么。非常感谢你提前。
def main():
# create a list
myList = []
number_of_values = input('Please enter number of values: ')
# Display the total of the list elements.
print('the list is: ', create_list(number_of_values))
print('the total is ', get_total(myList))
# The get_total function accepts a list as an
# argument returns the total sum of the values in
# the list
def get_total(value_list):
total = 0
# calculate the total of the list elements
for num in value_list:
total += num
#Return the total.
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = input('Please enter number: ')
myList.append(num)
return myList
main()
原文由 HenryDev 发布,翻译遵循 CC BY-SA 4.0 许可协议
在
main
你创建了空列表,但没有分配create_list
结果给它。您还应该将用户输入转换为int
: