' NoneType'使用Try and Except块时出错

时间:2014-05-21 20:44:51

标签: python exception-handling null-pointer invalid-argument

我尝试了一个奇怪的问题,除了我用来捕捉无效数据进入一个简单的黑杰克游戏我正在编写.....

def PickNumberOfPlayers():
    global log

    try:
        inputs = int(input("How Many Players Would You Like?: "))
        PlayersNumber = inputs
        log.write("How Many Players Would You Like?: \n")
        return PlayersNumber

    except ValueError:
        print("Try Typing in A Valid Number")
        log.write("Try Typing in A Valid Number\n")
        PickNumberOfPlayers()

然后我有一个GameStart()方法,它启动了许多方法调用:

def GameStart():
    global ListOfPlayers

    for i in range(0, int(PickNumberOfPlayers())):
        name = input("What Would You Like This Players Name To Appear As?:")
        ListOfPlayers.update({name: Player(0, name)})

    for key, value in ListOfPlayers.items():
        value.AccountSetup()
        value.Bet()

    for key, value in ListOfPlayers.items():
        value.PlayerDeal()
    Dealer.Deal() 

当我运行代码并输入正确的值(有效整数)时,没有问题。当我第一次输入无效数字(字符串或字符)时,我收到相应的消息" 尝试键入有效数字,然后当我输入有效整数时,我得到错误 -

    for i in range(0, int(PickNumberOfPlayers())):
TypeError: int() argument must be a string or a number, not 'NoneType' 

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

当您在PickNumberOfPlayers()中致电except时,您不会返回其值。请改为return PickNumberOfPlayers()

答案 1 :(得分:1)

您应该修改PickNumberOfPlayers以始终返回int。

def PickNumberOfPlayers():
    global log

    while 1:
        try:
            return int(input("How Many Players Would You Like?: "))
        except ValueError:
            print("Try Typing in A Valid Number")
            log.write("Try Typing in A Valid Number\n")