Python中exit、return、sys.exit()等使用实例和区别

yipeiwu_com5年前Python基础

有这样一道题目:  字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.

我最初的代码是:

复制代码 代码如下:

#!/usr/bin/env python

import string
import keyword
import sys

#Get all keyword for python
#keyword.kwlist
#['and', 'as', 'assert', 'break', ...]
keyWords = keyword.kwlist

#Get all character for identifier
#string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
#string.digits  ==> '0123456789'
charForId = string.letters + "_"
numForId = string.digits

idInput = raw_input("Input your words,please!")

if idInput in keyWords:
    print "%s is keyword fot Python!" % idInput
else:
    lenNum = len(idInput)
    if(1 == lenNum):
        if(idInput in charForId and idInput != "_"):
            print "%s is legal identifier for Python!" % idInput
        else:
            #It's just "_"
            print "%s isn't legal identifier for Python!" % idInput

    else:
        if(idInput[0:1] in charForId):
            legalstring = charForId + numForId
            for item in idInput[1:]:
                if (item not in legalstring):
                    print "%s isn't legal identifier for Python!" % idInput
                    sys.exit(0)
            print "%s is legal identifier for Python!2" % idInput
        else:
            print "%s isn't legal identifier for Python!3" % idInput
    

代码完毕后,我测试每一条分支,测试到分支时,必须输入_d4%等包含非法字符的标识符才能进行测试,我最初以为,sys.exit(0)---正常退出脚本,sys.exit(1)非正常退出脚本,但是实际情况是/9sys.exit(1),仅输出返回码不同):

复制代码 代码如下:

  if (item not in legalstring):
      print "%s isn't legal identifier for Python!" % idInput
     sys.exit(0)

Input your words,please!_d4%
_d4% isn't legal identifier for Python!

Traceback (most recent call last):
  File "E:/python/idcheck.py", line 37, in <module>
    sys.exit(0)
SystemExit: 0
>>>

由此可见,这样做没有达到我预期如下输出的效果,那么,问题在哪里呢?在于sys.exit()始终会抛出一个SystemExit异常。

复制代码 代码如下:

Input your words,please!_d4%
_d4% isn't legal identifier for Python!

复制代码 代码如下:

#!/usr/bin/env python

import string
import keyword
import sys
import traceback

try:
    #Get all keyword for python
    #keyword.kwlist
    #['and', 'as', 'assert', 'break', ...]
    keyWords = keyword.kwlist

    #Get all character for identifier
    #string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    #string.digits  ==> '0123456789'
    charForId = string.letters + "_"
    numForId = string.digits

    idInput = raw_input("Input your words,please!")

    if idInput in keyWords:
        print "%s is keyword fot Python!" % idInput
    else:
        lenNum = len(idInput)
        if(1 == lenNum):
            if(idInput in charForId and idInput != "_"):
                print "%s is legal identifier for Python!" % idInput
            else:
                #It's just "_"
                print "%s isn't legal identifier for Python!" % idInput

        else:
            if(idInput[0:1] in charForId):
                legalstring = charForId + numForId
                for item in idInput[1:]:
                    if (item not in legalstring):
                        print "%s isn't legal identifier for Python!" % idInput
                        sys.exit()
                print "%s is legal identifier for Python!2" % idInput
            else:
                print "%s isn't legal identifier for Python!3" % idInput

except SystemExit:
    pass
except:
    traceback.print_exc()

上面的代码获取sys.exit()抛出的SystemExit异常。

return:在定义函数时从函数中返回一个函数的返回值,终止函数的执行。

exit:下面的代码中,如果把sys.exit()替换成exit,则exit仅仅跳出离它最近的for循环, print "%s is legal identifier for Python!2" % idInput语句会被输出,这里,exit的作用类似于break. 但实际上break和exit作用并不同

复制代码 代码如下:

                for item in idInput[1:]:
                    if (item not in legalstring):
                        print "%s isn't legal identifier for Python!" % idInput
                        sys.exit()
                print "%s is legal identifier for Python!2" % idInput

相关文章

Python3 安装PyQt5及exe打包图文教程

Python3 安装PyQt5及exe打包图文教程

环境: Python 3.6.4 + Pycharm Professional 2017.3.3 + PyQt5 + PyQt5-tools ① Python 3 安装 Python 3...

Python3 获取一大段文本之间两个关键字之间的内容方法

用re或者string.find.以下是re代码 import re #文本所在TXT文件 file = '123.txt' #关键字1,2(修改引号间的内容) w1 = '123...

Python编码时应该注意的几个情况

在编程过程中,多了解语言周边的一些知识,以及一些技巧,可以让你加速成为一个优秀的程序员。对于Python程序员,你需要注意一下本文所提到的这些事情。你也可以看看Zen of Python...

Python学习笔记之For循环用法详解

本文实例讲述了Python学习笔记之For循环用法。分享给大家供大家参考,具体如下: Python 中的For循环 Python 有两种类型的循环:for 循环和 while 循环。fo...

基于python实现把图片转换成素描

基于python实现把图片转换成素描

这篇文章主要介绍了基于python实现把图片转换成素描,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 导语: 你是否还在为当时年少时没...