python核心编程之-python对象

检查类型(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()

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,868评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,550评论 18 399
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,672评论 0 4
  • 高铭玉阅读 1,328评论 0 0
  • 不管窗外多大风雨,回到屋内便能安心熟睡 奔波后疲惫躺下,呼吸着满满的安全感 我偷偷着羡慕家乡的亲朋们 前路依旧,不...
    易落阅读 8,893评论 0 4

友情链接更多精彩内容