在函数中运行 try 和 except 并重新运行会导致 NoneType 返回.我该如何解决这个问题?



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

例如:如果一个问题要求 y/n 响应,并且用户输入"d"或其他内容作为响应,则程序将使用 except 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()

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

我发现的是:
get_choice()返回 None.
在 get_choice 中,如果输入无效,它实际上不会返回任何内容。哦不!所以你返回 None,在 None 上调用 .lower(( 会引发异常。

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

get_bet(( 中有一个类似的错误,只是一个提醒,你可以用同样的方式解决它。

总的来说,很棒的游戏。

.lower(( 只在字符串上运行,使用 input(( 定义一个变量会使它不注册为字符串。 相反,请尝试这样的事情。

def set_choice():
choice = input("Want to bet on a coin toss?", 'y','n')
def choice():
choice = set_choice()
return choice
choice = choice.lower()

最新更新