我想重复输入“ g 1 2 3”之类的内容,并在每次输入数字时将它们添加到变量中。我制作了一个测试程序,但是输出错误例如如果我输入“ g 1 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)

07-27 19:31