python new

 

 

#-*- coding:utf-8 -*-
#1.#可以用来注释1
#'''三个单引号也可以用来注释多行
'''这里是注释
   可以注释多行
   注释结束'''
   
import sys
 
def main():
    testBase()
    testPhase()
    testString()
    testList()
    testMetaArray()
    testSet()
    testDictionary()
    testIterate()
    testFunction()
    testYield()
    testObjectAndClass()

def testBase():
    print("hello world")
    #换行代表一条语句的结束,也可以在同一行上使用分号来隔开多条语句
    a = 3; b = 26.3
    '''python是一种动态类型的语言,在程序执行的过程中,可以将
    变量名绑定到不同的值,而且这些值可以属于不同的类型。赋值运算
    符的作用仅仅是在名称和值之间创建一种关联。'''
    a = 2.5
    #这里给a赋值另外一种数据类型的值
    #python不会指定所需缩进的量,只要在一个代码块中保持一致即可。但通常使用4个空格。
    print("%3d %0.2f" %(a, b))  #这里能强制转换?
    a = 4
    print(format(a, "2d"), format(b, "0.3f"))
    print("{0:3d} {1:0.2f}".format(a, b))

def testPhase():
  #代码缩进只要在一个代码块中保持一致即可
    a = 1
    b = 2
    if a < b:
        print("aa<bb")
    
    if a > b:
        pass  # do nothing
    else:
        print("aaa<bbb")
  
    if a < b:
        print("a < b")
    else :
        print("a >= b")
  
    #还可以使用关键字or、and、not
    #使用符号\一行写不完可以换行。\后面不能有空格
    if a < b and 1 == 1 \
            and not(a > b):
        print("ok")
    else:
        print("no")

    #python没有switch语句,只能使用elif语句
    if 5 == a :
        print("a: 5")
    elif 4 == a:
        print("a: 4")
    elif 3 == a:
        print("a: 3")
    else:
        print("a is not 5、4、3")  
    

    f = open("foo.txt")  #返回一个文件对象
    line = f.readline()
    while line:
        print(line, end='')  #end=''将忽略换行符
        line = f.readline()
    f.close
    
    print("------")
    
    for line in open("foo.txt"):
        print(line, end='')    
    a = 3
    b = 32.5
    f = open("out", "w")
    while a > 0:
        b -= 1
        print("%3d %0.2f" %(a, b), file=f)
        a -= 1   #python里面没有a++
    f.close()
    
    print("------")
    '''
    sys.stdout.write("Enter your name:\n")
    name = sys.stdin.readline()
    print(name)'''

def testString():
    #字符串可以使用单引号、双引号、三引号(包括3个双引号和3个单引号)
    #使用单引号或双引号时,字符串必须在一个逻辑行上面
    a = 'hello a'
    b = "hello b"
    c = '''hello
    c'''
    d = """hello
dddd"""
    print(c)
    print(d)

    c = a[6]
    print("c:", c);
    #切片运算s[i:j]
    d = a[:4]
    print(d)
    d = a[2:4]
    print(d)
    d = a[3:]
    print(d)
    
    #两个字符串相加    
    x = "23"
    y = "45"
    d = x + y
    print(d)  #"2345"
    d = int(x) + int(y)
    print(d)  #68
    
    #str() repr() format()可以将非字符串值转换为字符串形式
    #str生成的输出与print语句得到的输出相同
    #repr()表示某个对象的精确值
    d = "hahaha:" + str(x)
    
def testList():
    #列表
    names = ["muhe221", "123", "456"]
    a = names[2]
    names.append("caoming")   #附加
    names.insert(2, "Thomas") #插入
    names[0] = "muhe222"
    print(names)
    names[1:3] = [1, 2]
    print(names)
    myList = names[:2]  #切片运算
    print(myList)
    myList = names + myList   #使用+运算符
    print(myList)
    
    print("-------")
    names = ["muhe221", [1, 2, "3"], "123", "456"]
    print(names)
    a = names[1]
    print(a)
    a = names[1][2]
    print(a)
    
    #创建列表
    names = [] #创建空的列表
    names = list() #创建空的列表

def testMetaArray():
    #元组
    stock = ('GOOG', 100, 490.10)
    #即使没有圆括号也能识别元组
    address = "www.baidu.com", 80
    #获取元组的值
    a, b, c = stock
    #元组与列表类似,都支持索引、切片和连接
    #但是创建元组后不能修改他的内容(无法替换、删除、插入)
    #元组是不可变的,所以他们内存更为紧凑,不会占据额外空间
    
    #文件格式为"name, shares, price"
    '''
    filename = "portfolio.csv"
    portfolio = []
    for line in open(filename)
        fields = line.split(",")
        name = fields[0]
        shares = int(fields[1])
        price = float(fields[2])
        stock = (name, shares, price)  #创建元组
        portfolio.append(stock)
    print(portfolio[0])
    print(portfolio[0][1])
    '''
    
    #创建元组
    a = ()
    b = (1, )
    c = 1, 

def testSet():
    print("----------testSet()------------")
    #集合:一组无序,不重复的对象
    s = set([3, 5, 9, 10])
    t = set("hello")
    print(s)  # {9, 10, 3, 5}
    print(t)  # {'h', 'l', 'o', 'e'}
    
    #集合支持一系列操作:并集、交集、差集、对称差集
    a = set([1, 2, 3, 4])
    b =  set([3, 4, 5, 6])
    c = a | b  #并集
    print(c)
    c = a & b  #交集
    print(c)
    c = a - b  #差集
    print(c)
    c = a ^ b  #对称差集,在a或b中,但不同时出现的对象
    print(c)
    #使用add 和update添加
    a.add(5) #添加一项
    print(a)
    a.update([6, 7]) #添加多项
    print(a)
    #使用remove删除
    a.remove(5)
    print(a)

def testDictionary():
    print("--------testDictionary()----------")
    #字典就是一个关联数组或散列表,其中包括通过关键字索引的对象
    stock = {
        "name" : "GOOG",
        "shares" : 100,
        "price" : 490.10
    }
    print(stock)
    name = stock["name"]
    value = stock["shares"]
    stock["shares"] = 110  #修改
    stock["date"] = "2018-07-21"  #插入
    print(stock)
    
    #使用in运算测试某个内容是否是字典成员
    if "price" in stock:
        p = stock["price"]
    else:
        p = 0
    print(p)
    #或者用下面的写法
    p = stock.get("price", 0)
    print(p)
    #获得关键字列表
    stockHead = list(stock)
    print(stockHead)
    #删除字典的元素
    del stock["price"]
    print(stock)
    
    
    #创建字典的两种方式,python中使用字典要比其他数据结构更好
    a = {}
    a = dict()
    
def testIterate():
    #迭代与循环
    for n in [1, 2, 3]:
        print(n)
    #range(i, j, [步长值]) 步长值默认是1,如果起始值省略则起始值为0
    for n in range(1, 4):
        print(n)
    for n in range(2, 5, 2):
        print(n)

def testFunction():
    print("------testFunction()------")
    x = minus(3, 1)
    print(x)
    x, y = divide(8, 3)
    print(x, y)

def minus(a, b):
    c =  a - b
    return c

def divide(a, b):
    c = a // b
    d = a % b
    return (c, d) #返回元组

def testYield():
    print("-----testYield()-------")
    c = countdown(5)
    a = c.__next__()
    print(a)
    a = c.__next__()
    print(a)
    b = next(c)
    print(b)
    b = next(c)
    print(b)
    b = next(c)
    print(b)
    
def countdown(n):
    print("counting donw")
    while n > 0:
        yield n
        print("yield ok")
        n -= 1
        
def testObjectAndClass():
    print("-----testObjectAndClass()--------")
    items = [23, 2]
    #dir()函数可以列出对象上的可用方法
    print(dir(items))
    
    s = Stack()  #创建一个栈
    s.push("a")
    s.push(4)
    s.push([3, 4, 5])
    s.print()
    x = s.pop()
    s.print()
    del s   #删除s
    
class Stack(object):  #Stack继承object
    #每个方法方法中第一个参数始终指向本身,名为self
    #以双下划线开始和结束的方法是特殊方法。
    #__init__用于创建对象后初始化该对象
    def __init__(self):
        self.stack = []
    def push(self, object):
        self.stack.append(object)
    def pop(self):
        #涉及对象属性的所有操作都必须显示引用self变量
        return self.stack.pop() 
    def print(self):
        print(self.stack)
    def length(self):
        return len(self.stack)

def testException():
    try:
        f = open("file.txt", "r")
        #或者手动触发异常
        #raise RuntimeError("you can raise exception by yourself")
    except IOError as e:
        print e        


if __name__=='__main__':
    main()

 

posted @ 2018-07-17 21:54  牧 天  阅读(187)  评论(0)    收藏  举报