我想重复输入“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)
我是一名优秀的程序员,十分优秀!