【问题标题】:Python 3.3: Can't get a function to return anything other than NonePython 3.3:无法让函数返回 None 以外的任何内容
【发布时间】:2013-08-16 16:50:48
【问题描述】:

所以,下面是相关代码:

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() 处,但我在这里和其他地方检查过,我看不出它有什么问题。

【问题讨论】:

    标签: python function python-3.x return nonetype


    【解决方案1】:

    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!')
    

    【讨论】:

    • 啊哈.. 伙计,我应该用“移动”进行测试,我只是痴迷于只尝试 1!如果我尝试使用“移动”,我敢打赌我可以弄清楚。非常感谢马丁。你会说使用字典而不是 if/elif 测试的优点是什么?它确实看起来不那么复杂/更优雅。
    • 映射更紧凑,更容易扩展,如果需要可以传递。查找也更快;只需要一个测试。
    猜你喜欢
    • 1970-01-01
    • 2023-03-27
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多