首页 > 解决方案 > 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次,所以如果有人可以修复我的代码,我将非常感激。

标签: pythonif-statementprinting

解决方案


我不知道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") 

推荐阅读