1

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)
0

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot for the help, for some reason if i do something like "g 100 2 3" "g 1 2 3" "g 1 2 3" the output is 300

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.