为什么在每次输入后不添加变量?

时间:2019-06-29 00:20:36

标签: python loops

该代码旨在每次在其变量上加1,但最终结果是,所有变量仍为0。

我是新手,只是测试了一些基本代码,应该是投票系统。

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

当我运行代码时:

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

我希望输出为:

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

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:4)

您需要分配加法结果:

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

您还可以使用复合赋值运算符:

if vote == "A":
  A += 1
elif vote == "B":
  B += 1
elif vote == "C":
  c += 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")
     break
 else:
     print ("That's not an option. Try again and Vote A,B or C")

输出:

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

答案 1 :(得分:3)

A + 1的结果未分配给任何内容,您应该执行A = A + 1,或者用较短的符号表示相同: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")