Skip to content Skip to sidebar Skip to footer

Python 3.7.3 Inconsistent Code For Song Guessing Code, Stops Working At Random Times

I have a python code that is a song guessing game, you are given the artist and the songs first letter, I used 2 2d arrays with on being the artist and the other being the song. I

Solution 1:

random.randint is inclusive in both ends. randint(0, 10) will return a number in the range

0 <= _ <= 10.

However Python uses 0-based indexes.

If li is [1, 2, 3] then len(li) is 3, but li[3] does not exist.

Only li[0], li[1] and li[2] do.


When you are doing

ArtCount = len(artist)
randNum = int(random.randint(0, ArtCount))
randArt = artist[randNum]

You are asking for a number in the range 0 <= n <= len(artist). If n == len(artist) then artist[n] will cause an IndexError.

BTW, randint returns an int (hence the int in its name). int(randint(...)) is totally unnecessary.

You should either ask for a random number in the range 0 <= n <= len(artist) - 1 or simply use random.choice:

randArt = random.choice(artist)

You may want to catch an IndexError just in case artist is an empty list:

try:
    randArt = random.choice(artist)
except IndexError:
    print('artist list is empty')

Post a Comment for "Python 3.7.3 Inconsistent Code For Song Guessing Code, Stops Working At Random Times"