2

所以,这里是相关的代码:

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”有什么值,它总是没有打印,“ifchoice == 1”块永远不会运行。所以我猜这个函数根本没有返回一个值,所以错误可能出在 action() 中的 return() 处,但我在这里和其他地方检查过,我看不出它有什么问题。

4

1 回答 1

4

input()总是返回一个字符串,但您正在测试整数。使它们成为字符串:

if choice in ('1', "move"):
    return 1

您输入choice的内容与您的任何测试都不匹配,因此函数在没有达到显式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!')
于 2013-08-16T16:54:30.987 回答