Python 3.3:Can';t获取一个函数以返回除None以外的任何内容

Python 3.3:Can';t获取一个函数以返回除None以外的任何内容,python,function,python-3.x,return,nonetype,Python,Function,Python 3.x,Return,Nonetype,以下是相关代码: def action(): print("These are the actions you have available:") print("1 - Change rooms") print("2 - Observe the room (OUT OF ORDER)") print("3 - Check the room(OUT OF ORDER)") print("4 - Quit the game") choice = in

以下是相关代码:

def action():
    print("These are the actions you have available:")
    print("1 - Change rooms")
    print("2 - Observe the room (OUT OF ORDER)")
    print("3 - Check the room(OUT OF ORDER)")
    print("4 - Quit the game")

    choice = input("What do you do?\n> ")
    if choice in (1, "move"):
        return(1)
    elif choice in (4, "quit"):
        return(4)

play = True

while play == True:
    ###some functions that aren't relevant to the problem
    choice = action()
    print(choice)
    if choice == 1:
        change_room()
        ## more code...
该函数始终返回None。我把print(choice)放在那里,看看“choice”有什么值,它总是prinss none,而“if choice==1”块永远不会运行。所以我猜函数根本没有返回值,所以错误可能是在return()的in action()中,但我在这里和其他地方检查过,看不出它有什么问题。

input()
总是返回字符串,但您是针对整数进行测试的。让它们成为字符串:

if choice in ('1', "move"):
    return 1
您输入的
选项
与您的任何测试都不匹配,因此函数结束时从未到达显式的
return
语句,Python将恢复为默认返回值
None

更好的是,用字典替换整个
if/elif/elif
树:

choices = {
    '1': 1,
    'move': 1,
    # ...
    '4': 4,
    'quit': 4,
}

if choice in choices:
    return choices[choice]
else:
    print('No such choice!')
input()
始终返回一个字符串,但您正在测试整数。让它们成为字符串:

if choice in ('1', "move"):
    return 1
您输入的
选项
与您的任何测试都不匹配,因此函数结束时从未到达显式的
return
语句,Python将恢复为默认返回值
None

更好的是,用字典替换整个
if/elif/elif
树:

choices = {
    '1': 1,
    'move': 1,
    # ...
    '4': 4,
    'quit': 4,
}

if choice in choices:
    return choices[choice]
else:
    print('No such choice!')

啊。。伙计,我应该用“移动”来测试,我只是痴迷于用1!如果我试着用“移动”的话,我打赌我一定能找到答案。非常感谢Martijn。您认为使用字典而不是if/elif测试的优点是什么?使用dict,它看起来不那么复杂/更优雅。映射更紧凑,更容易扩展,并且可以在需要时传递。查找速度也更快;只需要一次测试。啊。。伙计,我应该用“移动”来测试,我只是痴迷于用1!如果我试着用“移动”的话,我打赌我一定能找到答案。非常感谢Martijn。您认为使用字典而不是if/elif测试的优点是什么?使用dict,它看起来不那么复杂/更优雅。映射更紧凑,更容易扩展,并且可以在需要时传递。查找速度也更快;只需要一次测试。