用Python写一段检查输入合法性的小程序

#!/usr/bin/env python

import string

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

print 'Welcome to the Identifier Checker v1.0'
print 'Testees must be at least 2 chars long.'
inp = raw_input('Identifier to test:')
"""
只有当输入大于两个字符,并且首字符为字母或下划线,剩余字符为数字、字母、下划线,才为正确
"""
if len(inp) > 1:
    if inp[0] not in alphas:
        print 'Invalid: first symbol must be alphabetic'
    else:
        for otherChar in inp[1:]:
            if otherChar not in alphasnums:
                print 'Invalid: other symbol must be alphanumeric'
                break
        else: #yes,this 'else' belongs to 'for',will execute this line after 'for' body
            print 'OK as an identifier.'

你可能感兴趣的:(Python)