Josh Eaton
Josh Eaton

Reputation: 21

Why isn't the variable added after each input?

The code is designed to add 1 to its variable each time, but in the end result, all variables are still 0.

I'm new and just testing out some basic code, it's supposed to be a voting system.

while True:
 A=0
 B=0
 C=0
 vote=input("A, B or C")

 if vote == 'A':
     A + 1
 elif vote == 'B':
     B + 1
 elif vote == 'C':
     C + 1
 elif vote == 'end':
     print ("A got",A,"votes, B got",B,"votes, C got",C,"votes")
 else:
     print ("That's not an option. Try again and Vote A,B or C")

When I run the code:

A, B or C?A

A, B or C?B

A, B or C?C

A, B or C?A

A, B or C?B

A, B or C?end

A got 0 votes, B got 0 votes, C got 0 votes

I expected the output to be:

"A got 2 votes,B got 2 votes, C got 1 votes"

Any help would be greatly appreciated :)

Upvotes: 0

Views: 50

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44087

You need to assign the result of your addition:

if vote == "A":
  A = A + 1
elif vote == "B":
  B = B + 1
elif vote == "C":
  C = C + 1

You could also use a compound assignment operator:

if vote == "A":
  A += 1
elif vote == "B":
  B += 1
elif vote == "C":
  c += 1

And you need to declare them outside of the loop, otherwise you're reassigning them every time.

Full code:

A = 0
B = 0
C = 0
while True:
 vote = input("A, B or C? ")

 if vote == "A":
     A += 1
 elif vote == "B":
     B += 1
 elif vote == "C":
     C += 1
 elif vote == "end":
     print ("A got", A, "votes, B got", B, "votes, C got", C, "votes")
     break
 else:
     print ("That's not an option. Try again and Vote A,B or C")

Output:

A, B or C? A
A, B or C? B
A, B or C? C
A, B or C? A
A, B or C? B
A, B or C? end
A got  2  votes, B got  2  votes, C got  1  votes

Upvotes: 4

Ismael Padilla
Ismael Padilla

Reputation: 5566

The result of A + 1 isn't being assigned to anything, you should do A = A + 1, or the same in shorter notation: A += 1.

A=0
B=0
C=0
while True:

 vote=input("A, B or C")

 if vote == 'A':
     A += 1
 elif vote == 'B':
     B += 1
 elif vote == 'C':
     C += 1
 elif vote == 'end':
     print ("A got",A,"votes, B got",B,"votes, C got",C,"votes")
 else:
     print ("That's not an option. Try again and Vote A,B or C")

Upvotes: 3

Related Questions