题目
标识符合法性检查,要求如下:
1.首字母以及后续字母要用字母、数字或者下划线表示
2.如果输入的字符为python关键字能判定输入的字符是关键字并且输出格式如下(检查无误并且是关键字!)
import string
import keyword
checkedchar = input('请输入将要检查的字符串: ')
checkchar = string.ascii_letters + '_' + string.digits
specialchar = keyword.kwlist
if len(checkedchar) == 1:
if checkedchar not in checkchar:
print('Error!')
else:
print('NoError')
if len(checkedchar) > 1:
for i in range(len(specialchar) - 1):
if checkedchar == specialchar[i]:
print('检查无误并且是关键字!')
if checkedchar[0] not in checkchar:
print('输入格式错误并且第一位就错了!')
else:
for otherchar in checkedchar[1:]:
if otherchar not in checkchar:
print('输入格式错误!')
break
else:
print('输入格式没有错误!')
注意python中不允许把关键字用来做标识符。因此在这里我们用keyword模块中的keyword.kwlist生成一个包含所有关键字的列表,如果输入有关键字可以用循环来判定。
for otherchar in checkedchar[1:]:
这一段代码中要注意字符串也是可迭代对象,因此这段代码可以访问chackedcahr中除了第一个字母意外的任意一个字母并在循环中进行判断。输出结果如下:
请输入将要检查的字符串: def
检查无误并且是关键字!
输入格式没有错误!
请输入将要检查的字符串: ***
输入格式错误并且第一位就错了!
请输入将要检查的字符串: 1
NoError
请输入将要检查的字符串: 111
输入格式没有错误!
请输入将要检查的字符串: 1**
输入格式错误!
为了容易判别程序可能出现的错误,可以在打印错误结果时打印出不同的文字。