Python I';我正在创建一个程序来接受N个数字,并使用列表查找其和
我是Python新手。我正在创建一个程序来接受N个数字,并使用列表查找其和。如何将数字动态添加到列表中?这就是我现在的处境Python I';我正在创建一个程序来接受N个数字,并使用列表查找其和,python,list,Python,List,我是Python新手。我正在创建一个程序来接受N个数字,并使用列表查找其和。如何将数字动态添加到列表中?这就是我现在的处境 n=int(input("enter the value of n")) list=[] for i in range(0,n): a=int(input("enter the value of number",i+1)) list.append(a) Sum=0 for num in list: Sum=Sum+ num print("sum is
n=int(input("enter the value of n"))
list=[]
for i in range(0,n):
a=int(input("enter the value of number",i+1))
list.append(a)
Sum=0
for num in list:
Sum=Sum+ num
print("sum is",Sum)
使用
n=int(输入(“输入n的值”)
获取n
后,您可以使用列表理解将n
输入添加到列表中:
numbers=[int(input()) for i in range(n)]
要获得这些数字的总和,只需使用内置函数sum()
:
完整代码:
n=int(input("N:"))
numbers=[int(input()) for i in range(n)]
total=sum(numbers)
print("sum is: ",total)
输入示例:
enter the value of n: 5
1
2
3
4
5
输出:
sum is: 15
谢谢大家的帮助,但我纠正了我的错误,并提出了最适合我的代码
n=int(input("enter the value of n"))
lst=[]
for i in range(0,n):
a=int(input("enter the number"+str(i+1)))
list.append(a)
Sum=0
for num in lst:
Sum=Sum+ num
print("sum is",Sum)
AAAA那你的问题是什么?好的:最后一个!=列表您必须使用append,如果列表为空,则无法使用索引。如何使用append?有文档、教程和教科书演示了基本功能。您还没有发布尝试;哪里有问题?Python区分大小写。变量Sum
和Sum
不相同。除非您了解结果,否则不应使用list
作为变量名。谢谢您的回答,但我已使用append更新了上面的代码。但是CMD显示第5行是语法错误你的代码第5行是什么,我为我的答案写的程序只有4行?
n=int(input("enter the value of n"))
lst=[]
for i in range(0,n):
a=int(input("enter the number"+str(i+1)))
list.append(a)
Sum=0
for num in lst:
Sum=Sum+ num
print("sum is",Sum)