为什么我的函数在某些条件下返回错误的值?

时间:2015-11-18 07:58:21

标签: python python-3.x

我有一个名为getFirstPlayer的函数。用户必须输入B(黑色)或W(白色)。

一切都按预期工作,但仅在最初输入可接受的值时才有效。识别出未接受的值(W,w,B,b以外的任何值)并再次调用该函数,然后当用户输入接受的值时,不返回任何内容。

例如:

User.order(:points) 返回值:无

但是,当您在第一次尝试时输入“B”时,正确返回整数1。

A
Specify which player will move first: B for black, W for white
C
Specify which player will move first: B for black, W for white
B

我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果您在else块中输入try子句,则不会返回任何内容。

(这不是你应该使用递归的东西。)

更明智的功能看起来像这样:

def getFirstPlayer() -> int:
    while True:
        firstPlayer = input("Specify which player will move first: B for black, W for white: ")
        if firstPlayer in ('W','w'):     # One way to handle upper- and lowercase
            return 2
        elif firstPlayer.lower() == 'b': # Another way 
            return 1

答案 1 :(得分:0)

None是没有其他内容时返回的值,这是else块中最后一个try子句的情况。尝试:

def getFirstPlayer() -> int:
    while True:
        try:
            firstPlayer = str(input())

            if firstPlayer == 'W' or firstPlayer == 'w':
                return 2
            elif firstPlayer == 'B' or firstPlayer == 'b':
                return 1
            else:
                print("Specify which player will move first: B for black, W for white")
                return getFirstPlayer() # changed this line

        except ValueError:
            print("Specify which player will move first: B for black, W for white")
            continue
        else:
            break
相关问题