Skip to content Skip to main navigation Skip to footer

Python中exit、return、sys.exit()的不同之处

下面的内容主要介绍了Python中exit、return、sys.exit()的不同之处,欢迎大家参考:

有这样一道题目: 字符串标识符.修改例 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

Python中exit、return、sys.exit()的不同之处就是这样,欢迎大家参考。。。。

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.