Python

Moderators: None (Apply to moderate this forum)
Number of threads: 400
Number of posts: 1055

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Somehow this won't work. Posted by kratosaurion7 on 2 Jun 2010 at 8:46 PM
I wanted to do this little program that shows a list of names and give them random numbers. The user have to memorize each name-number set and must give the correct number to the name chosen randomly.

def mainGame():
    playing = True 


    #The lists are matching names with their numbers.
    nameList = ('Joe', 'Alice', 'Bob', 'Eve')
    #numberList = (returnRandom(0, 10), returnRandom(0, 10), returnRandom(0, 10), returnRandom(0, 10))  #Return random is a function I made that spits out a random number given the range. Shortcut for random.randint(min, max)

    for i in range(0, len(numberList)):
        print nameList[i], ":", numberList[i]

    while playing:
        rand = returnRandom(0, len(numberList))
        
        print "What is %s's number?" % nameList[rand]

        if raw_input("Choice: ") == numberList[rand]:
            playing = False



    print "Congratulation, you finished this minigame !"

Output:
Joe : 2
Alice : 10
Bob : 5
Eve : 4

What is Bob's number?
Choice: 5

(I know I should use a dictionary, but I can't seem to work it out. Any help is appreciated though.)

The problem is that after a few iterations I get this error:
print "What is %s's number?" % nameList[rand]
IndexError: tuple index out of range

It can be after 3 iterations, or 5 or 6. And I don't why, its not supposed to go out of range at all ! Halp.

Report
This post has been deleted. Posted by joeab on 3 Jun 2010 at 12:45 AM
This post has been deleted.
Report
This post has been deleted. Posted by joeab on 3 Jun 2010 at 12:46 AM
This post has been deleted.
Report
Re: Somehow this won't work. Posted by bubbatremell on 8 Jun 2010 at 10:22 AM
The highest index of a list is len(list) - 1 (b/c it's zero-indexed).
Say my list looks like this:
a = [1, 2, 3]
Then,
len(a) == 3
However,
a[2] == 3
a[3] == error

In your code, after a while, it tries to hit an index beyond the range of the tuple. This happens because it's allowed to look up nameList[len(numberList)], but the highest index is len[numberList - 1].

Hope that helps!



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.