如何从Python中的多个输入添加输入

时间:2014-07-08 03:53:10

标签: python

我想输入类似" 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)

1 个答案:

答案 0 :(得分:1)

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)