Python Forum
Trivia2 Loop problem?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trivia2 Loop problem?
#1
So I'm getting the constant error of there being it reading the loop too many times and I was wondering how to fix that, I'm currently working in school on the python learning book and on trivia 2 i'm starting to slip because of this problem.

#18_Trivia2

import sys

def open_file(file_name, mode):
   """Open a file"""
   try:
       the_file = open(file_name, mode)
   except IOError as e:
       print("Unable to open the file",file_name,"Ending program.\n", e)
       input("\n\nPress the enter key to exit")
       sys.exit()
   else:
       return the_file

def next_line(the_file):
   """Return next line fromthe trvia file, formatted"""
   line = the_file.readline()
   line = line.replace("/","\n")
   return line

def next_block(the_file):
   """Return the next block of data from the trivia file."""
   category = next_line(the_file)
   question = next_line(the_file)

   answers = []
   for i in range(4):
       answers.append(next_line(the_file))

   correct = next_line(the_file)
   if correct:
       correct = correct[0]

   explanation = next_line(the_file)

   points = next_line(the_file)

   return category, question, answers, correct, explanation, int(points)

def welcome(title):
   """Welcome the player and get his/her name"""
   print("\t\tWelcome to Trivia Challenge!\n")

def main():
   trivia_file = open_file("trivia.txt","r")
   title = next_line(trivia_file)
   welcome(title)
   score = 0

   #Get first block
   category, question, answers, correct, explanation, points = next_block(trivia_file)
   while category:
       #ask a question
       print(category)
       print(question)
       for i in range(4):
           print("\t", i + 1, "-", answers[i])


       #Get answer
       answer = input("What's your answer?: ")
       #Check answer
       if answer == correct:
           print("\nRight!",end = " ")
           score += points
       else:
           print("\nWrong.",end = " ")
       print(explanation)
       print("Score: ",score,"\n\n")

       #Get next block
       category, question, answers, correct, explanation, points = next_block(trivia_file)

   trivia_file.close()
   print("That was the last question!")
   print("You're final score is",score)

main()
input("Press the enter key to exit")
The error it has been showing me is:
Output:
Traceback (most recent call last):  File "C:\Users\milll929\Downloads\Mills_17_Trivia.py", line 81, in <module>    main()  File "C:\Users\milll929\Downloads\Mills_17_Trivia.py", line 75, in main    category, question, answers, correct, explanation, points = next_block(trivia_file)  File "C:\Users\milll929\Downloads\Mills_17_Trivia.py", line 41, in next_block    return category, question, answers, correct, explanation, int(points) ValueError: invalid literal for int() with base 10: ''
Which my teacher has told me it is a problem with looping and it doing it too many times, can I please get some help?
Thank you!
Reply
#2
(Jun-06-2017, 02:08 PM)milll929 Wrote:    points = next_line(the_file)
 
   return category, question, answers, correct, explanation, int(points)

You're reading lines from a file, and converting those lines to an int. Based on the error, it looks like one of the lines is blank.

>>> int("5")
5
>>> int("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
So either get rid of the blank line, or test to see if the line actually has contents before trying to cast it to an int, or use try/except to handle the error.
Reply
#3
Thank you for helping, I am still finding the problem of if I do not cast points as an int, it will immediately come up with

[output]
Traceback (most recent call last):
 File "C:\Users\milll929\Downloads\Mills_17_Trivia.py", line 81, in <module>
   main()
 File "C:\Users\milll929\Downloads\Mills_17_Trivia.py", line 68, in main
   score += points
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
Reply
#4
Well, you didn't use any of the suggestions nilamo gave. You need to cast it as an int in order to add it to another int, you just need to handle cases where it isn't an int. Any easy way to do this is with isdigit:

>>> '32'.isdigit()
True
>>> 'Five'.isdigit()
False
>>> ''.isdigit()
False
You can use this to detect a string containing an integer. Use an if statement to cast and add if it's an int, and to skip to the next line if it isn't. Or take either of nilamo's other two suggestions.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with for loop Intellectual11 5 2,660 Aug-26-2021, 04:14 PM
Last Post: naughtyCat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020