Reputation: 81
I want to input something like "g 1 2 3" repeatedly and have the numbers add to a variable each time I enter them. I made a test program however the output is wrong e.g. if I enter "g 1 2 3" 3 times I would expect my variable to print "3" but it prints "0". What is wrong with my code?
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)
Upvotes: 1
Views: 213
Reputation: 46533
AddTot + Name1
does not modify AddTot
, as in the result won't be stored anywhere. Replace it with
AddTot += Name1 # same as `AddTot = AddTot + Name1`
That said, your program only uses the first input. To fix that, move NameMSplit = NameMarks.split()
within the loop body:
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)
As for further improvements, you can shorten your code a little:
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)
Upvotes: 1