简体   繁体   中英

Im getting an index error and im not sure why

So ive been working on a script for a course im doing and ive ran into an error

The basic idea of the program is a voting system but when working out who got the most votes the program hits an error the error reads

    if votes[0] > votes[1] and votes[0] > votes[2] and votes[0] > votes[3]:
IndexError: list index out of range

The full funtion is here:

def getwinner():
    if votes[0] > votes[1] and votes[0] > votes[2] and votes[0] > votes[3]:
        print("Congratulations candidate",cands[0],"You win")
        if votes[1] > votes[0] and votes[1] > votes[2] and votes[1] > votes[3]:
            print("Congratulations candidate", cands[1], "You win")
            if votes[2] > votes[0] and votes[2] > votes[1] and votes[2] > votes[3]:
                print("Congratulations candidate", cands[2], "You win")
                if votes[3] > votes[0] and votes[3] > votes[1] and votes[3] > votes[2]:
                    print("Congratulations candidate", cands[3], "You win")

                    if votes[0] == votes[1] and votes[0] == votes[2] and votes[0] == votes[3]:
                        print("We have a tie")
                        if votes[1] == votes[0] and votes[1] == votes[2] and votes[1] == votes[3]:
                            print("We have a tie")
                            if votes[2] == votes[0] and votes[2] == votes[1] and votes[2] == votes[3]:
                                print("We have a tie")
                                if votes[3] == votes[0] and votes[3] == votes[1] and votes[3] == votes[2]:
                                    print("We have a tie")

The votes are saved to an array called "votes" and candidate names are saved to "cands".The candidate names line up with the votes in the "votes" array. But could someone explain the issue and also is there a simpler, less long winded way of going about this? Thanks

You can greatly simplify your logic and easily extend it to more then 4 players:

max_vote = max(votes)
if votes.count(max_vote) > 1:
    print("We have a tie")
else:
    winner_index = votes.index(max_vote)
    print("Congratulations candidate", cands[winner_index], "You win")

Seems like your list, votes , doesn't have 4 values. It'll complain that there's nothing at index 3 if there's nothing at index 3, and for no other reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM