首页 > 解决方案 > 在函数中运行 try 和 except 并重新运行会导致 NoneType 返回。我该如何解决?

问题描述

我正在开发一个简单的程序,该程序允许用户在抛硬币时下注一些虚拟货币。一切正常,除非用户输入错误。

例如:如果一个问题要求 y/n 响应,而用户输入 'd' 或其他东西作为响应,程序将使用异常 ValueError 并重新运行该函数。但是,当重新运行该函数并且用户最终正确输入了某些内容时,它将导致进一步的错误。

Error: 

> AttributeError: 'NoneType' object has no attribute 'lower'

代码:

import time
import random

money = 5000
last_interest_time = time.time()


def interest():
    global money, last_interest_time
    if time.time() - last_interest_time > 5:
        prev_money = money
        money *= 0.1
        last_interest_time = time.time()
        print("You now have " + str(money) + " monies (+" + str(money - prev_money) + ") from interest")


def game():
    global money, last_interest_time
    print("You have " + str(money) + " monies.")
    choice = get_choice("Want to bet on a coin toss?", 'y','n')
    if choice.lower() == 'y':
        print("That's great!")
        choice = get_choice("What side do you want to bet on?", 'h', 't')
        bet_amount = get_bet()
        print('Flipping the coin...')
        time.sleep(1)
        side = random.choice(['h', 't'])
        if side == 'h':
            print("The coin landed heads!")
        elif side == 't':
            print('The coin landed tails!')
        if side == choice:
            print("You won and received " + str(bet_amount) + " monies!")
            money += bet_amount
        else:
            print("You lost the bet and " + str(bet_amount) + " monies!")
            money -= bet_amount
        game()
    elif choice.lower() == 'n':
        input('Oh well. Just type something if you want to bet again. ')
        game()


def get_choice(question, response_1, response_2):
    choice = input(question+" ("+response_1+'/'+response_2+'): ')
    if choice != response_1 and choice != response_2:
        print('Input is invalid. Must be '+response_1+'/'+response_2)
        get_choice(question, response_1, response_2)
    else:
        return choice


def get_bet():
    bet_amount = input("What amount do you want to bet?: ")
    try:
        if int(bet_amount) > money:
            print("You don't have enough money!")
            get_bet()
        else:
            return int(bet_amount)
    except ValueError:
        print('Invalid input. Must be a number')
        get_bet()


game()

标签: pythonfunctiontry-catch

解决方案


调试提示:每次都打印选择,这样您就可以看到它崩溃的原因!您可以稍后取出打印语句。

我发现的是:
get_choice()没有返回。
在 get_choice 中,如果输入无效,它实际上不会返回任何内容。不好了!因此,您返回 None,并且在 None 上调用 .lower() 会引发异常。

解决方案:
如果输入无效,则第二次运行 get_choice 时,您处于正确的轨道上。一个小调整:不只是运行 get_choice,而是返回 get_choice。

get_bet() 中也有类似的错误,只是提醒一下,您可以用同样的方法解决它。

总的来说,很棒的游戏。


推荐阅读