0

I am making a trivia game; I am still new to python. Where should I place my try and except statements to prevent the user entering a letter and an amount higher than xScore(a or b)?

class Question:
    def __init__(self, question, answera, answerb, answerc, answerd, correct):
        self.question = question
        self.answers = [answera, answerb, answerc, answerd]
        self.correct = correct
    def ask(self):
        print(self.question)
        for n in range(0, 4):
            print("   ", n + 1, ")", self.answers[n])
        answer = int(input("enter your answer >"))
        return answer == self.correct

def right(x):
    x * 2
    return int(x)



def questions1():
    aScore = 10
    print('you are able to wager up to', aScore)
    bet = int(input('Enter points to wager:'))
    question1 = Question("What does the NFL stand for?", "National Football League", "National Fun Live", "No Fun League",
                         "Narcs Fuzz and Larp", 1)
    if question1.ask() == True:
        print("You are correct")
        aScore += right(bet)
    else:
        print("incorrect")
        aScore -= bet

    print('you are able to wager up to', aScore)
    bet = int(input('Enter points to wager:'))
    question2 = Question("Who won the superbowl last year (2016)", "Atlanta Falcons", "New England Patriots", "Carolina Panthers",
                         "Toronto Maple Leafs", 2)
    if question2.ask() == True:
        print("You are correct")
        aScore += right(bet)
    else:
        print("incorrect")
        aScore -= bet

1 Answers1

1

To prevent user entering a letter (or any non-integer) using a try... except, you can put the try...except around the input:

while True:
    try:
        answer = int(input("enter your answer >"))
    except ValueError:
        print('Answer must be an integer.')
    else:
        break

This will keep prompting until the user enters an integer. The else statement runs if the except is not hit, so the flow breaks out of the loop.

To prevent the user entering an amount higher than their score, you can test their input after the try...except

while True:
    try:
        answer = int(input('Enter points to wager:'))
    except ValueError:
        print('Answer must be an integer.')
    else:
        if answer < aScore:
            break
        else:
            print("You don't have enough points for that wager!")
Shaun Taylor
  • 326
  • 2
  • 6