重新再回头来看看python,原来都是用的Pyhon2,好多都忘了,更新下知识,今年的第一本书,简单记录下。
下载地址:https://pan.baidu.com/s/19qpUFZlegEWd3Zlhc-HMSQ 提取码: evnu
print(*objects, sep=' ', end='\n', file=sys.stdout)
print("cisco","huawei") #默认多字符串的间隔符为空格
print("cisco","huawei",sep = "&" ) #可以加上sep修改间隔符
print("cisco","huawei",sep="*",end="*********") #设置结尾符
f = open("d:/tmp/1.txt","w+") #写入文件前,先打开文件,并设置写属性。
print("cisco","huawei",sep="*",file=f)
def calc (h):
kg = h/1000
return '其实重量为' + str(kg) + 'kg'
a = int(input("请输入重量,单位为g" + "\n"))
print ( calc(a))
import math
def shuxue(a,b):
c = a**2 + b**2
d = math.sqrt(c)
return "The right triangle third side's length is " + str(d)
a = int(input("输入第一个直角边" + "\n"))
b = int(input("请输入第二个直角边" + "\n"))
print(shuxue(a,b))
def create(name,msg):
path = "d:/tmp/"
full_path = path + name + ".txt"
file = open(full_path,"w")
file.write(msg)
file.close()
print("done")
create("test","hello world")
create("test","ni mei")
def login():
password = ['!@#', '123']
retries = 3
while retries > 0 :
pwd = input('请输入密码: ' )
if pwd == password[-1]:
print('恭喜你,成功登陆!')
break
elif pwd == password[0]:
newpwd = input('请输入新的密码: ')
password.append(newpwd)
del password[-2]
print('你的密码已更改为'+password[-1])
break
else:
print('密码错误,请重新输入!')
retries = retries - 1
else:
print('密码错误超过3次,账户琐定10分钟')
login()
def create():
path = 'd:/tmp/'
for i in range(1,11):
full_path = path + str(i) + '.txt'
f = open(full_path,'w')
f.close()
create()
def invest(amount,rate=5,time=8):
for i in range(1,time + 1):
total = float(amount) * ((1 + float(rate) / 100) ** float(i))
print('year '+ str(i) + ': $'+ str(total))
a = input('principal amount: ')
invest(a)
def invest(amount,rate=5,time=8):
for i in range(1,time + 1):
total = float(amount) * ((1 + float(rate) / 100) ** float(i))
print('year '+ str(i) + ': $'+ str(total))
a = input('principal amount: ')
invest(a)
import random
while True:
BBB = input('你来猜猜大小:')
a = random.randrange(1,7)
b = random.randrange(1,7)
c = random.randrange(1,7)
s = [a,b,c]
if 11 <= sum(s) <= 18:
print('你的点数为大,',end=' ')
if BBB == '大':
print('你赢了')
elif BBB == '小':
print('你输了')
else:
print('但是你输入错误了,请重新输入')
elif BBB == 'exit':
break
else:
print('你的点数为小,',end=' ')
if BBB == '大':
print('你输了了')
elif BBB == '小':
print('你赢了')
else:
print('但是你输入错误了,请重新输入')
import random
#摇骰子系统
def roll_points(times=3,points='none'):
if points is 'none':
points = []
while times > 0 :
point = random.randrange(1,7)
points.append(point)
times = times - 1
return points
#比大小系统
def roll_result(total):
if total > 10:
return 'Big'
elif total < 11:
return 'Small'
#游戏系统
def start_game(start):
while start > 0:
print('<<<<<<<<< GAME START >>>>>>>>>')
your_choice = input('"Big" or "Small":')
while your_choice in ['Big', 'Small']:
money = input('How much you wanna bet:')
if not money.isdigit() :
break
else:
if int(money) > start:
break
else:
print('<<<<<<<<< Roll >>>>>>>>>')
points = roll_points()
print('The points is {},'.format(points),end=' ')
if roll_result(sum(points)) == your_choice:
result = 'You Win'
totals = start + int(money)
else:
result = 'You Lose'
totals = start - int(money)
print(result)
start = totals
break
if your_choice == 'bye':
break
else:
print('You have only {}, play again with "Big"/"Small" or exit with "bye"'.format(start))
else:
print('GAME OVER')
start_game(1000)
CN_mobile = [134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705]
CN_union = [130,131,132,155,156,185,186,145,176,1709]
CN_telecom = [133,153,180,181,189,177,1700]
def phone():
number = input('Enter Your number:')
if not number.isdigit():
print('please enter right number')
phone()
else:
num1 = int(number[0:3])
num2 = int(number[0:4])
if len(number) != 11:
print('Invaild length,your name should be in 11 digits')
phone()
elif num1 in CN_telecom or num2 in CN_telecom:
print('Operator:CN_telecom')
print('we should send verification code to your phone:{}'.format(number))
elif num1 in CN_union or num2 in CN_union:
print('Operator:CN_union')
print('we should send verification code to your phone:{}'.format(number))
elif num1 in CN_mobile or num2 in CN_mobile:
print('Operator:CN_moblie')
print('we should send verification code to your phone:{}'.format(number))
else:
print('No such a operator')
phone()
phone()
zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。
zip([iterable, ...])
num = [1,2,3,4,5,6]
str = ['1st','2nd','3th','4th','5th','6th','7th']
test = {i:j for i,j in zip(num,str)}
print(test)
{1: '1st', 2: '2nd', 3: '3th', 4: '4th', 5: '5th', 6: '6th'}
import time
a = []
t0 = time.perf_counter()
for i in range(1,20000000):
a.append(i)
print(time.perf_counter() - t0,'seconds process time')
t1 = time.perf_counter()
b = [i for i in range(1,20000000)]
print(time.perf_counter() - t1,'seconds process time')
运行后,区别还是有的,虽然循环的次数确实比较多,在书上比较老的版本中20000次的差距都比较明显,确实py也在进步,并且和书上的例子用的函数也不一样,用的并不是上面的time.perf_counter()
而是用time.clock()
,但是这个函数在3.8就会被移除的,当前版本是3.7,所以我就换了新的函数。 3.2525775990000003 seconds process time 1.4710991059999996 seconds process time字典推导式也差不多,如下:
g = {i:j for i,j in zip(range(1,6),'abcde')}
str.split(str="",num=string.count(str))[n]
str:表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素。num:表示分割次数,如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量。[n]:表示选取第n个分片。 str = 'www.cisco.com'
a = str.split('.')
b = str.split('.')[1]
c = str.split('.',1)
print(a)
print(b)
print(c)
输出结果
['www', 'cisco', 'com']
cisco
['www', 'cisco.com']
string.punctuation
代表着所有的标点符号。 import string
list = ['.baynk5211.vicp.cc', '_baynk5211.vicp.cc']
list2 = [a.strip('.') for a in list]
list3 = [a.strip(string.punctuation) for a in list]
print(list2,list3,sep='\n')
运行结果
['baynk5211.vicp.cc', '_baynk5211.vicp.cc']
['baynk5211.vicp.cc', 'baynk5211.vicp.cc']
num = [ 1,5,7,2,9.11,8]
str = ['z','d','a','f','cisco','huawei']
print(sorted(num))
print(sorted(str,reverse=True)) #默认情况下reverse=False
list = [('c',4),('a',3),('d',1),('b',2)]
print(sorted(list,key=lambda x:x[0]))
print(sorted(list,key=lambda x:x[1]))
运行结果
[1, 2, 5, 7, 8, 9.11]
['z', 'huawei', 'f', 'd', 'cisco', 'a']
[('a', 3), ('b', 2), ('c', 4), ('d', 1)]
[('d', 1), ('b', 2), ('a', 3), ('c', 4)]
import string
def counter(path):
with open(path,'r') as txt:
words = [a.strip(string.punctuation).lower() for a in txt.read().split()]
list1 = [a for a in words]
list2 = [words.count(a) for a in words]
dic = {x:y for x,y in zip(list1,list2)}
result1= sorted(dic.items(),key=lambda x:x[1],reverse=True)
result2= sorted(dic.items(),key=lambda x:x[1])
m = 0
n = 0
max = [ ]
min = [ ]
while True:
if result1[m][1] > result1[m+1][1]:
max.append(result1[m][0])
print('文章中出现次数最多的是{},一共出现了{}次。'.format(sorted(max), result1[m][1]))
break
else:
max.append(result1[m][0])
m = m + 1
while True:
if result2[n][1] < result2[n+1][1]:
min.append(result2[n][0])
print('文章中出现次数最少的是{},一共出现了{}次。'.format(sorted(min),result2[n][1]))
break
else:
min.append(result2[n][0])
n = n + 1
counter( 'd:/tmp/Walden.txt')
#类属性如果被重新赋值,是否会影响到类属性的引用?
class TestA:
attr = 1
obj_a = TestA()
TestA.attr = 42
print(obj_a.attr)
#会的!!!
#实例属性如果被重新赋值,是否会影响到类属性的引用?
class TestB:
attr = 1
obj_a = TestB()
obj_b = TestB()
obj_a.attr = 42
print(obj_b.attr)
#不会
#类属性实例属性具有相同的名称,那么.后面引用的将会是什么?
class TestC:
attr = 1
def __init__(self):
self.attr = 42
obj_a = TestC()
print(obj_a.attr)
print(TestC.__dict__)
print(obj_a.__dict__)
#是实例属性
txt = 'd:/tmp/test.txt'
with open(txt,'r') as f:
print(f.read())
print('*'*100)
with open(txt, 'r') as f:
print(f.readline())
print(f.readline(2)) #这里尝试一下指定字符
print(f.readline())
print('*'*100)
with open(txt, 'r') as f:
print(f.readlines())
运行结果为import random
fn_path = 'D:/Tmp/f_name.txt'
ln_path = 'D:/Tmp/l_name.txt'
fn = []
ln = []
with open(fn_path,'r',encoding='utf_8') as f:
for line in f.readlines():
fn.append(line.strip('\n'))
fn = list(set(fn))
with open(ln_path,'r',encoding='utf_8') as f:
for line in f.readlines():
ln.append(line.strip('\n'))
ln = list(set(ln))
class FakeUser:
def fake_name(self,amount=1):
while amount > 0:
full_name = random.choice(fn)+random.choice(ln)
yield full_name
amount -= 1
def fake_gender(self,amount=1):
while amount > 0:
gender = random.choice(['男','女'])
yield gender
amount -= 1
class SnsUser(FakeUser):
def fake_age(self,amount=1):
while amount > 0:
age = random.randrange(10,60)
yield age
amount -= 1
def information(num):
name_list = []
gender_list = []
age_list = []
user_a = SnsUser()
#这里SnsUser里面没有fake_name方法,但是也可以直接调用,这就是调用了父类函数
for name in user_a.fake_name(num):
name_list.append(name)
for gender in user_a.fake_gender(num):
gender_list.append(gender)
for age in user_a.fake_age(num):
age_list.append(age)
n = 0
while n < num :
print(name_list[n],gender_list[n],age_list[n])
n += 1
information(10)
焦萃 女 14
陈珠 女 27
秦森 女 21
贾司 男 22
字朗 女 56
翁骄 女 42
运珊 男 23
出惕 女 50
封麟 女 10
鹿璨 女 41
第八章则是讲解第三方库,这里就不记录了,确实非常适合新手看,很简单易懂,如果有时间的话,大概2天左右就看完了,比较推荐,但是由于知识点很粗糙,还需要再去看一些知识点比较系统的书籍,下本书见。