__MagicPower
Do one thing and do it best!

导航

 
#!/usr/bin/env python
#--*-- coding:utf-8 --*--
"""
标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母,下划线或者数字
这个例子只检查长度大于等于2的标志符
"""

import string
alphas = string.letters + '_'
nums = string.digits

def menu():
    print 'Welcome to the Identifier Checker v1.0'
    print 'Testees must be at least 2 chars long.'
    #myInput = raw_input('Identifier to test?\n')


def runidchk(myInput):
    if len(myInput) > 1: #判读长度是否大于2
        if myInput[0] not in alphas: #首字母是否以字母或者下划线
            print "invalid:first symbol must be alphabetic"
        else: 
            for otherchar in myInput[1:]:
                if otherchar not in alphas + nums:
                    print "invalid:remaining symbols must be alphabetic"
                    break
                else:
                    print "okay as an Identifier"

if __name__ == '__main__':
    while True:
        menu()
        runidchk(raw_input('Identifier to test?\n'))

 

running result:

kevins-MacBook-Pro:chapter06 kevin$ python idcheck.py 
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.


Identifier to test?
__hello
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.


Identifier to test?
333
invalid:first symbol must be alphabetic

 

posted on 2015-12-02 13:40  __MagicPower  阅读(518)  评论(0编辑  收藏  举报