在哪里放置try和except语句以防止用户输入:字母和以上给定金额?

时间:2017-12-09 21:54:38

标签: python python-3.x

我正在做一个琐事游戏;我还是python的新手。我应该在哪里放置我的try和except语句,以防止用户输入字母和高于xScore(a或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 个答案:

答案 0 :(得分:1)

为防止用户使用try... except输入字母(或任何非整数),您可以try...except围绕input

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

这将继续提示,直到用户输入整数。 else语句在未except未命中的情况下运行,因此流break不在循环中。

为防止用户输入高于其得分的金额,您可以在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!")