在python中,如何停止正在执行的函数中的代码?

2024-05-22 18:52:23 发布

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

在Python3.2中,有没有一种方法可以停止函数的其余部分的执行?在

基本上,我正在创建一个登录系统作为我的课程作业的一个概念,但我在任何地方都找不到答案。在

我的代码分为两个文件,一个logger,它用一个日志文件处理输入和输出,以及主要类,如数据库连接、登录代码本身等

下面是处理获取用户输入的代码,我感兴趣的是第3行和第4行,它们将“quit”转换为“QUIT0x0”,以尽量减少意外调用quit代码的机会。在

def getInput(input_string, type):
    result = input(input_string)
    if result.lower == 'quit':
            result = 'QUIT0x0'
    #log the input string and result
    if type == 1:
            with open(logFile, 'a') as log_file:
                    log_file.write('[Input] %s \n[Result] %s\n' %(input_string, result))
                    return result
    #no logging
    elif type == 2:
            return result
    #undefined type, returns 'Undefined input type' for substring searches, and makes a log entry
    else:
            result = '[Undefined input type] %s' %(input_string)
            output(result, 4)
            return result

这是处理从用户数据库中删除用户记录的代码,我感兴趣的是如何使第4行和第5行工作并停止执行函数的其余部分:

^{pr2}$

提前谢谢你, 汤姆


Tags: 文件函数代码用户log数据库inputstring
1条回答
网友
1楼 · 发布于 2024-05-22 18:52:23

“退出函数”称为return

def deleteUser(self):
  self.__user = getInput('Enter the username you want to delete records for: ', 1)
  if self.__user == 'QUIT0x0':
    return
  else:
    # ...

但是,由于您已经使用了if/else,因此不应该执行else分支,因此返回是不必要的。你也可以在里面放一个pass

^{pr2}$

或者使用以下方法:

def deleteUser(self):
  self.__user = getInput('Enter the username you want to delete records for: ', 1)
  if self.__user != 'QUIT0x0':
    # ...

甚至使用提前退换货:

def deleteUser(self):
  self.__user = getInput('Enter the username you want to delete records for: ', 1)
  if self.__user == 'QUIT0x0':
    return
  # ...

相关问题 更多 >

    热门问题