如何将Python中的多个输入添加到一起

如何将Python中的多个输入添加到一起,python,Python,我想反复输入像“G123”这样的内容,并在每次输入时将数字添加到变量中。我编写了一个测试程序,但是输出是错误的,例如,如果我输入“G1 2 3”3次,我希望我的变量打印“3”,但它打印“0”。我的代码有什么问题 AddTot = int(0) NameMarks = input("Please input your name followed by your marks seperated by spaces ") NameMSplit = NameMarks.split() while Nam

我想反复输入像“G123”这样的内容,并在每次输入时将数字添加到变量中。我编写了一个测试程序,但是输出是错误的,例如,如果我输入“G1 2 3”3次,我希望我的变量打印“3”,但它打印“0”。我的代码有什么问题

AddTot = int(0)
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
NameMSplit = NameMarks.split()
while NameMarks != 'Q':
    Name1 = int(NameMSplit[1])
    Name2 = int(NameMSplit[2])
    Name3 = int(NameMSplit[3])
    AddTot + Name1
    NameMarks = input("Please input your name followed by your marks seperated by spaces ")
print(AddTot)

AddTot+Name1
不会修改
AddTot
,因为结果不会存储在任何地方。换成

AddTot += Name1 # same as `AddTot = AddTot + Name1`
也就是说,您的程序只使用第一个输入。要解决此问题,请在循环体中移动
NameMSplit=NameMarks.split()

AddTot = int(0)
NameMarks = input("Please input your name followed by your marks seperated by spaces ")
while NameMarks != 'Q':
    NameMSplit = NameMarks.split() # here
    Name1 = int(NameMSplit[1])
    Name2 = int(NameMSplit[2])
    Name3 = int(NameMSplit[3])
    AddTot += Name1
    NameMarks = input("Please input your name followed by your marks seperated by spaces ")
print(AddTot)
至于进一步的改进,您可以稍微缩短代码:

AddTot = 0 # or int() without argument
say = "Please input your name followed by your marks seperated by spaces "
NameMarks = input(say)
while NameMarks != 'Q':
    marks = [int(x) for x in NameMarks.split()[1:]]
    AddTot += marks[0]
    NameMarks = input(say)

print(AddTot)

非常感谢您的帮助,出于某种原因,如果我做一些像“G1002 3”G123“G123”这样的事情,输出是300