zl程序教程

您现在的位置是:首页 >  Python

当前栏目

第6关:Python的标识符

2023-04-18 14:06:11 时间
#应该是最难的一关了吧,补课了很多知识
# keyword.iskeyword()用于判断关键字
# string扩展库
# and 和 or 的逻辑判断
import string
import keyword
n = input("Please Input Identifier:")
digits = string.digits #包含0-9的数字字符串
letters = string.ascii_letters#包含所有大小写字母的字符串
punctuation = string.punctuation#包含所有标点符号的字符串
Underline = '_' 
lenth = len(n)
#一共有五个
if lenth >= 2:
#第一个if是是判断输入的字符个数
    if n[0] in letters or n[0] in Underline:
    #第二个if是判断输入的字符串是不是以下划线或字母开头
        for i in range(1,lenth):
            if n[i] in digits or  n[i] in letters or n[i] in Underline == True:
             # 第三个if是判断当输入的字符串以字母或下划线开头时,
             # 剩余是否包含字母、数字、下划线以外的字符。
                fact = True
                continue                               
            else:
                fact = False
                break                
        if fact == True:
        #第四个if是根据第三个if判断结果输出不同语句
            if keyword.iskeyword(n)==True:
            #第五个if是判断是否为关键字
                print('SyntaxError: {} is a keyword'.format(n))
            else:
                print('{} is a valid identifier'.format(n))
        else:
            print('invalid:identifier symbols must be alphanumeric')
    else:
          print('invalid: first symbol must be alphabetic')       
else:
    print('input error')

平台会对你编写的代码进行测试:
测试输入:Please Input Identifier:a
预期输出:input error
测试输入:Please Input Identifier:_abc
预期输出:_abc is a valid identifier
测试输入:Please Input Identifier:if
预期输出:SyntaxError: if is a keyword
测试输入:Please Input Identifier:123a
预期输出:invalid: first symbol must be alphabetic
测试输入:Please Input Identifier:abc :
预期输出:invalid:identifier symbols must be alphanumeric