Python投票计数
变量有效性
函数内可以调用外部的全局变量,但是必须使用global语句在函数内声明该变量为全局变量。
PHP中文网:python如何在一个函数里使用全局变量global a,b,c
# Python投票计数 实在懒得校验输入值有效性了,睡觉(¦3[▓▓])
# -*-coding=utf-8-*-
MTY = 0
LRJ = 0
LRY = 0
LRB = 0
def WriteUserFigure(data):
global MTY, LRJ, LRY, LRB
if data == "梦天幼":
MTY = MTY+1
elif data == "路人甲":
LRJ = LRJ+1
elif data == "路人乙":
LRY = LRY+1
else:
LRB = LRB+1
return MTY, LRJ, LRY, LRB
print("欢迎进入2021年度优秀个人投票系统\n\n候选人:\n梦天幼,路人甲,路人乙,路人丙。")
print("--------------------------")
a = input("第1位投票,请输入候选人名字:")
MTY, LRJ, LRY, LRB = WriteUserFigure(a)
b = input("第2位投票,请输入候选人名字:")
MTY, LRJ, LRY, LRB = WriteUserFigure(b)
c = input("第3位投票,请输入候选人名字:")
MTY, LRJ, LRY, LRB = WriteUserFigure(c)
d = input("第4位投票,请输入候选人名字:")
MTY, LRJ, LRY, LRB = WriteUserFigure(d)
print("--------------------------")
print("结果如下:")
print("梦天幼:", str(MTY), "票\n")
print("路人甲:", str(LRJ), "票\n")
print("路人乙:", str(LRY), "票\n")
print("路人丙:", str(LRB), "票")
StrHead = "胜利者为:"
if MTY > LRJ and MTY > LRY and MTY > LRB:
print(StrHead, "梦天幼")
elif LRJ > MTY and LRJ > LRY and LRJ > LRB:
print(StrHead, "路人甲")
elif LRY > MTY and LRY > LRJ and LRY > LRB:
print(StrHead, "路人乙")
else:
print(StrHead, "路人丙")