Python3学习笔记之基础教程

时间:2022-06-18 06:36:09

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

__author__ = 'Administrator'

import subprocess
cmd="cmd.exe"
begin=101
end=200
while 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 keyword
print(keyword.kwlist)
#变量所指的对象类型
a,b,c,d=20,5.5,True,4+3j
print(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]=22
print(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组成的list
print(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,1
while 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 = 100
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
print("Sum of 1 until %d: %d" % (n,sum))

#for循环
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
    print(x)
#break
edibles = ["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=4
h=5
print("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 argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

#可变参数的使用
def arithmetic_mean(*args):
    sum = 0
    for x in args:
        sum += x
    return sum
print(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 deque
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.append("Graham")          # Graham arrives
print(queue.popleft())                 # The first to arrive now leaves
print(queue.popleft())                # The second to arrive now leaves
print(queue)                          # Remaining queue in order of arrival
#遍历字典数据结构
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
    print(k, v)