有這樣一道題目: 字符串標識符.修改例 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
新聞熱點
疑難解答