为什么我的函数做了它应该做的事情,然后它不继续通过代码?

2024-09-29 19:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个选择你自己的冒险游戏,我有一个功能来检查你在控制台中输入的内容是否可以接受。在开始时,您只能键入“打开灯光”,如果您键入任何其他内容,它将返回错误,并提示您键入实际操作。我的问题是,在你键入一些不被接受的内容后,它将不会让你在出错后继续。你知道吗

actions = ['help','turn light on',]

def errorcheck(player_input):
    if player_input in actions:
        error = False
        return()
    else:
        error = True
        while error == True:
            print('i dont know what you mean by',player_input)

            player_input = input('>')

            if player_input in actions:
                error = False
            else:
                error = True

print('welcome to TITLE')
print('type help at anytime to see your options')
print('">" that symbol promts you to do something')
print('')
print('you wake up, its dark')



player_input = input('>')

errorcheck(player_input)

if error == False:
    if player_input == ('help'):
        playerhelp = True
        while playerhelp == True:
            print('you can: turn light on')
            playerhelp = False

Tags: toyouactionsfalsetrue内容input键入
2条回答

首先,绝对不要在主代码中使用函数中的局部变量。如果要访问error,应按如下方式返回:

def errorcheck(player_input):
    if player_input in actions:
        error = False
    else:
        error = True
        while error == True:
            print('i dont know what you mean by',player_input)

            player_input = input('>')

            if player_input in actions:
                error = False
            else:
                error = True
    return error

其次,也难怪程序在进入help之后会停止,因为在那之后就没有代码了。如果你想让用户不断地被要求输入一些东西,你必须在整个解析逻辑中加入一个循环。。。你知道吗

errorcheck可能修改它作为参数接受的player_input。它是一个新的局部变量,与全局player_input无关。你知道吗

一个简单的解决方案是使player_input成为一个全局变量,但这将是一个糟糕的反模式解决方案,原因如下:

  • 全局变量往往导致混乱、难以调试的代码
  • 一个函数最好做一件事,那件事最好是它的名字所暗示的。你知道吗

相反,让errorcheck只检查输入的名称。你知道吗

def errorcheck(player_input):
    return player_input not in actions

player_input = None

while errorcheck(player_input):
    player_input = input('>')

此时将errorcheck作为函数似乎有点多余。你并不真的需要它:

player_input = None

while player_input not in actions:
    player_input = input('>')

相关问题 更多 >

    热门问题