python - IF 和 ELIF 函数和 FOR 函数
问题描述
x = int(input("Numbers of Voters:"))
a = input("Candidate 1:")
b = input("Candidate 2:")
c = input("Candidate 3:")
for i in range(x):
print ("Enter Your 1st choice ")
for a in range(1):
a= input("1st Choice: ")
for i in range(x):
print ("Enter your 2nd choice ")
for b in range(1):
b= input("2nd Choice: ")
for i in range(x):
print ("Enter your 3rd choice ")
for c in range(1):
c= input("3rd Choice: ")
if (a > b) and (a > c):
print("Winner is", a)
elif (b > a) and (b > c):
print("Winner is", b)
else (c > a) and (c > b):
print("Winner is", c)
我的代码不起作用,它应该询问选民人数和三名候选人的姓名,然后每个选民必须从最喜欢的候选人到最不喜欢的候选人排名,当投票结束时,它应该打印“Winner is”和最喜欢的那个。我不知道我是否做得正确,因为每次更改时都会出错。我知道用python编码,我不知道如何打印第一选择,第二选择和第三选择然后传递给第二个选民所以我打印第一选择3次然后第二选择3次和第三选择3次,所以如果有人可以修复我的代码,我将非常感激。
解决方案
我不知道python,所以我知道下面有语法错误。逻辑是你需要让它工作的东西。
简而言之:计算每个候选人。为每个候选者分配一个数值。3如果是第一选择,2如果是第二选择,1如果是第三选择。最后,计数最多的人是赢家。
x = int(input("Numbers of Voters:"))
a = input("Candidate 1:")
b = input("Candidate 2:")
c = input("Candidate 3:")
aCount=0
bCount=0
cCount=0
for i in range(x):
candidate1 = input("First Choice")
if candidate1 == a :aCount=aCount+3
if candidate1 == b :bCount=bCount+3
if candidate1 == c :cCount=cCount+3
candidate2 = input("Second Choice")
if candidate2 == a :aCount=aCount+2
if candidate2 == b :bCount=bCount+2
if candidate2 == c :cCount=cCount+2
candidate3 = input("Third Choice")
if candidate3 == a :aCount=aCount+1
if candidate3 == b :bCount=bCount+1
if candidate3 == c :cCount=cCount+1
if candidate1>candidate2 and candidate1>candidate3 : print ("candidate 1 wins")
推荐阅读
- mysql - 如何在我的 sql 中有效地删除数据而不消耗时间
- angular - Angular 2+ 中客户端的动态元标记
- docker - 有没有办法在 Jitsi 中拥有易于扩展的客户端?
- python - 欧拉-马斯切罗尼常数
- algorithm - 在这种情况下,我们如何检测这些点?
- android - 任务“:app:mergeDevDebugResources”执行失败
- git - 更改分支时不要删除 .gitignore 中的本地文件
- angular - Angular/HTML 中的 NgIf 和 NgElse
- javascript - 如何安全地公开显示 Firestore 子集合的 UID
- python - 如何为 scipy.signal.find_peaks 指定阈值