Error in python quiz that shouldn't exist

Viewed 32

I have been creating a quiz game, and have to select a random line from a file. In my main code, it isn't working, so I rewrote the code in a separate file.

#Import relevant modules
import csv
import time
import random

#declare placeholder variables
a=0
b=0


#create a random line function
def randomLine(fname):
    lines = open(fname).read().splitlines()
    return random.choice(lines)

def runQuiz():
    a=1
    c=0
    print ('Welcome to the Quiz!')
    while b == 0:
        chosenLine = randomLine('songlist.csv')
        print(chosenLine)
        while chosenLine[c] != ',':
            c += 1
        print (c)


#run the function
runQuiz()

This is the code, and when I run it it gives me the expected outputs then this error

Traceback (most recent call last):
  File "Z:/NEA2020/OneDrive_1_12-11-2020/2.py", line 29, in <module>
    runQuiz()
  File "Z:/NEA2020/OneDrive_1_12-11-2020/2.py", line 23, in runQuiz
    while chosenLine[c] != ',':
IndexError: string index out of range

Any idea what's causing it?

2 Answers
while chosenLine[c] != ',':
    c += 1

... will keep incrementing c until a comma is found in your line. A possible issue is there being no comma in the line, which will make it become too high and go too far.

However, I don't believe that's your actual problem here. You're not setting c back to 0 at the beginning of the while b == 0: loop ; so it enters a new iteration of the loop while still having the value it got from the previous random line. Which could make it try to access a value too high for the new random line right off the bat, hence generating an IndexError.

Also, you can replace

while chosenLine[c] != ',':
    c += 1
print (c)

by

print(chosenLine.index(','))

The above answer is correct.

You can did some thing like this

    while b == 0:
        global b
        chosenLine = randomLine('songlist.csv')
        print(chosenLine)
        while chosenLine[c] != ',':
            c += 1
        print (c)
        # include only one line or both as your requirements
        b = 1   # if you want only one line 
        c = 0 # if you want multiple lines 
Related