Python3学习笔记之基础教程

来源:互联网 发布:淘宝哪家卤味店好吃 编辑:程序博客网 时间:2024/05/11 12:11

参考网站:http://www.w3cschool.cc/python3/python3-tutorial.html

__author__ = 'Administrator'import subprocesscmd="cmd.exe"begin=101end=200while begin<end:    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,                       stdin=subprocess.PIPE,stderr=subprocess.PIPE)    p.stdin.write("ping www.baidu.com\n".encode())    p.stdin.close()    p.wait()    print  ('execution result:%s'%p.stdout.read())

__author__ = 'Administrator'#ide使用PyCharm  Python3使用实例#查看Python关键字import keywordprint(keyword.kwlist)#变量所指的对象类型a,b,c,d=20,5.5,True,4+3jprint(type(a),type(b),type(c),type(d))#字符串s = 'Yes,he doesn\'t'print(s,type(s),len(s))#字符串连接盒重复print('str'+'ing', 'my'*3)#Python字符串2种索引方式word = 'Python'print(word[0],word[5])print(word[-1],word[-6])#字符串截取word = 'ilovepython'print(word[1:5])print(word[:])print(word[-10:-6])#List(列表)的使用#列表是写在方括号之间、用逗号分隔开的元素列表。列表中元素的类型可以不相同:a = ['him', 25, 100, 'her']print(a)#list索引,串联,修改,删除a = [1, 2, 3, 4, 5]print(a[2])print(a + [6, 7, 8])a[0]=22print(a)#切片print(a[2:5])#删除a[2:5]=[]print(a)#元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号里a = (1991, 2014, 'physics', 'math')print(a, type(a), len(a))#集合(set)是一个无序不重复元素的集。student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}print(student)   # 重复的元素被自动去掉print('Rose' in student)#集合运算a = set('abracadabra')b = set('alacazam')print(a)print(a - b)# a和b的差集print(a | b) # a和b的并集print( a & b) # a和b的交集#http://www.w3cschool.cc/python3/python3-data-type.html#字典是一种映射类型(mapping type),它是一个无序的键 : 值对集合。关键字必须使用不可变类型,在同一个字典中,关键字还必须互不相同。dic = {}  # 创建空字典tel = {'Jack':1557, 'Tom':1320, 'Rose':1886}print(tel)print(tel['Jack']) # 主要的操作:通过key查询del tel['Rose']  # 删除一个键值对tel['Mary'] = 4127  # 添加一个键值对print(tel)print(list(tel.keys()))  # 返回所有key组成的listprint(sorted(tel.keys())) # 按key排序print('Tom' in tel)      # 成员测试print('Mary' not in tel) # 成员测试

__author__ = 'yunshouhu'import base64'''我是多行注释我是多行注释'''"""我也是多行注释我也是多行注释"""#幂运算print(5 ** 2)  # 5 的平方print(2 ** 7)  # 2的7次方print(2 ** 10)print(2 ** 20)#求斐波纳契数列a,b=0,1while b<10:    print(str(b),end=',')    a,b=b,a+b#base64编码和解码print("")s="我是字符串nihao"a=base64.b64encode(s.encode(encoding="utf-8"))print(a.decode())print(base64.b64decode(a).decode())age=int(input("age of the dog:"))print()if age<0:    print("this can hardly be true!")elif age==1:    print("about 14 humen years")elif age==2:    print("about 22 human years")elif age>2:    human=22+(age-2)*5    print("human years:",human)else:    print("hehe")#input("press return ")#while循环n = 100sum = 0counter = 1while counter <= n:    sum = sum + counter    counter += 1print("Sum of 1 until %d: %d" % (n,sum))#for循环languages = ["C", "C++", "Perl", "Python"]for x in languages:    print(x)#breakedibles = ["ham", "spam","eggs","nuts"]for food in edibles:    if food == "spam":        print("No more spam please!")        break    print("Great, delicious " + food)else:    print("I am so glad: No spam!")print("Finally, I finished stuffing myself")#步长for i in range(0, 10) :print(i)for i in range(0, 10, 3) :print(i)#pass语句什么都不做pass  # 等待键盘中断 (Ctrl+C)

__author__ = 'yunshouhu'#函数def hellword():    print("helloworld ok!")hellword()def area(width,height):    return width*height;def print_welcome(name):    print("Welcome ",name)w=4h=5print("width=",w," height=",h," area=",area(w,h))#全局变量和局部变量a = 4  # 全局变量def print_func1():    a = 17 # 局部变量    print("in print_func a = ", a)def print_func2():    print("in print_func a = ", a)print_func1()print_func2()print("a = ", a)#函数调用方式def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):    print("-- This parrot wouldn't", action, end=' ')    print("if you put", voltage, "volts through it.")    print("-- Lovely plumage, the", type)    print("-- It's", state, "!")parrot(1000)                                          # 1 positional argumentparrot(voltage=1000)                                  # 1 keyword argumentparrot(voltage=1000000, action='VOOOOOM')             # 2 keyword argumentsparrot(action='VOOOOOM', voltage=1000000)             # 2 keyword argumentsparrot('a million', 'bereft of life', 'jump')         # 3 positional argumentsparrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword#可变参数的使用def arithmetic_mean(*args):    sum = 0    for x in args:        sum += x    return sumprint(arithmetic_mean(45,32,89,78))print(arithmetic_mean(8989.8,78787.78,3453,78778.73))print(arithmetic_mean(45,32))print(arithmetic_mean(45))print(arithmetic_mean())#将列表当作队列使用from collections import dequequeue = deque(["Eric", "John", "Michael"])queue.append("Terry")           # Terry arrivesqueue.append("Graham")          # Graham arrivesprint(queue.popleft())                 # The first to arrive now leavesprint(queue.popleft())                # The second to arrive now leavesprint(queue)                          # Remaining queue in order of arrival#遍历字典数据结构knights = {'gallahad': 'the pure', 'robin': 'the brave'}for k, v in knights.items():    print(k, v)


0 0
原创粉丝点击