投票不是选举

2024-06-28 15:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

对四名候选人的选举进行计票的简单程序。 一次只能得到一张选票,四票候选人的票数由数字表示, 最后在屏幕上打印出获胜者。你知道吗

这是我的密码

candList = [0, 0, 0, 0]

while True:
    print '1 for First Candidate'
    print '2 for Second Candidate'
    print '3 for Third Candidate'
    print '4 for Fourth Candidate'
    print '5 for Exit Poll'

    cid = input('Enter Candidate Number to Vote: ')

    if cid == 5:
        break

    candList[cid - 1]

vote = max(candList)
candidate = candList.index(vote) + 1
print 'Winner is  Candidate', candidate, 'with', vote, 'Votes'

但问题是选票不算在内。。 我给1个候选人3票,但最终打印

Result is : Winner is  Candidate 1 with 0 Votes

Tags: 程序foriswithcandidateprintvote选票
3条回答

代码中有许多问题。你知道吗

首先,id是一个内置函数,不要使用id作为变量名。对于list秒也是如此,第15行(list[id-1])显然没有任何作用。第三,不应该使用eval将字符串转换为整数,而应该使用int。你知道吗

这段代码应该可以完成这项工作,但它仍然有一些警告:用户可以输入15或不是一个数字,程序将被终止,也不处理两个候选人获得相同票数的情况

lst = [0, 0, 0, 0]

while True:
    print '1 for First Candidate'
    print '2 for Second Candidate'
    print '3 for Third Candidate'
    print '4 for Fourth Candidate'
    print '5 for Exit Poll'

    cid = int(input('Enter Candidate Number to Vote: '))

    if cid == 5:
        break

    lst[cid - 1] += 1

vote = max(lst)
candidate = lst.index(vote) + 1
print 'Winner is  Candidate', candidate, 'with', vote, 'Votes'

你从不给list[cid - 1]赋值。您应该将该行更改为以下内容:

list[cid - 1] += 1

另外,我建议您不要使用list作为列表的名称。你知道吗

勾选此项您不更改相应的人数更改代码

list = [0, 0, 0, 0]

while True:
    print '1 for First Candidate'
    print '2 for Second Candidate'
    print '3 for Third Candidate'
    print '4 for Fourth Candidate'
    print '5 for Exit Poll'

    id = int(raw_input('Enter Candidate Number to Vote: '))

    if id == 5:
        break
#Change Here add the count
    list[id - 1] = list[id-1]+1

vote = max(list)
candidate = list.index(vote) + 1
print 'Winner is  Candidate', candidate, 'with', vote, 'Votes'

相关问题 更多 >