检查类型(typechk.py)
#!/usr/bin/env python
def displayNumType(num):
print num, 'is',
if isinstance(num, (int, long, float, complex)):
print 'a number of type:',type(num)._name_
else:
print 'not a number at all!'
displayNumType(-69)
displayNumType(9999999L)
displayNumType(98.6)
displayNumType(-5.2+1.9j)
displayNumType('xxx')
标识符检查(idcheck.py)
#!/usr/bin/env python
import string
alphas = string.letters + '_'
nums = string.digits
print 'Welcome to the Identfier Checker v1.0'
print 'Testees must be at least 2 chars long.'
myInput = raw_input("Identifier to test ? ")
if len(myInput) > 1:
if myInput[0] is not in alphas:
print '''invalid: first symbol must be
alphabetic'''
else:
for otherChar in myInput[1:]:
if otherChar not in alpha + nums:
print '''invalid: remaining
symbols must be alphanumeric'''
break
else:
print ''okay as an identifier''
#一般来说,从性能角度来考虑,把重复操作作为参数放到循环里面进行是非常低效的。可以考虑把重复进行运算操作的值做一个变量赋值保存,后续直接引用变量。
简单的Unicode字符串例子(uniFile.py)
#!/usr/bin/env python
CODEC='utf-8'
FILE='unicode.txt'
hello_out = u"Hello World\n"
bytes_out = hello_out.encode(CODEC)
f = open(FILE,"w")
f.write(bytes_out)
f.close()
f = open(FILE,"r")
bytes_in = f.read()
f.close()
hello_in = bytes_in.decode(CODEC)
print hello_in,
用列表来模拟堆栈(stack.py)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
stack = []
def pushit():
stack.append(raw_input(' Enter New string: ').strip())
def popit():
l = len (stack)
if l ==0:
print 'Cannot pop from an empty stack!'
else:
print 'Removed [',`stack.pop()`,']'
def viewstack():
print stack
def quitapp():
exit
CMDs = {'u': pushit,'o': popit,'v': viewstack}
def showmenu():
pr="""
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
pr="""
p(U)sh
p(O)p
(V)iew
(Q)uit
Enter choice: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].lower()
except (EOFError,KeyboardInterrupt,IndexError):
choice = 'q'
print '\n You picked: [%s]' % choice
if choice not in 'uovq':
print "Invalid option, try again"
else:
break
if choice == 'q':
break
CMDs[choice]()
if __name__ == '__main__':
showmenu()