当前位置:网站首页>Pass teacher liaoxuefeng's series of courses quickly 1
Pass teacher liaoxuefeng's series of courses quickly 1
2022-07-21 11:06:00 【ViviranZ】
def pfff(x,n=2,*,name,clss):
s=1
while n>0:
s=s*x
n=n-1
print(s,",the student is",name,"in class",clss)
return
https://www.liaoxuefeng.com/wiki/1016959663602400/1017024645952992
2021/7/27 Start as soon as possible
Catalog
Volatile variables 、 Keyword parameters and named keyword parameters **highly important
review :
python Its advantage lies in its perfect basic code base , The disadvantage is ( comparison C) Slow operation ( But the fact does not affect )
win+R→cmd Enter→python( The sign is >>>)
exit() sign out
If you use VS code, You need to switch directories
Then input and output :( Double quotation marks and single quotation marks can be used to represent strings )
Run with the command line :
python With “#” Start commenting , Express the format in indentation ( Therefore, you should check the indentation after copying and pasting ), Case sensitive , Escape character "\"
name=input('your name is: ')
print(name,"Say yohoho~ \\n"r'\n\\n')
print("Somalian Pirates We!")
print("Somalian",'Pirates',"We!")
About coding :
ASCII code ( Case letters + Numbers )→ Countries add their own language characters ( China :GB2312)→ Internationally Unicode( Usually two bytes )→ To simplify generation UTF-8( Different number of bytes , One English letter , Chinese characters are generally three, some four )
In computer memory , Unified use Unicode code , When you need to save to a hard disk or need to transfer , Just switch to UTF-8 code .
When editing with Notepad , Read from file UTF-8 The characters are converted to Unicode Characters in memory , After editing , Save it with Unicode Convert to UTF-8 Save to file .
When browsing the web , The server will dynamically generate Unicode Content to UTF-8 Then transfer to browser , So you can see a lot of source codes of web pages that are similar to
<meta charset="UTF-8" />
Information about , It means that the web page is using UTF-8 code .
print(ord(' Ha '))
print(chr(123456))
Python Basics :
List&Tuple:
List
Is the most commonly used variable form , Elements can be strings 、 Numbers 、 Boolean value, etc
chrters=['Pirates',"We"]
print(chrters)
print(len(chrters))
print(chrters[0])
print(chrters[-1])
chrters.append("!")
print(chrters)
chrters.insert(0,"Somalian")
print(chrters)
chrters.pop(3)
print(chrters)
chrters[2]="You"
print(chrters)
The running result is :
tuple
comparison list,tuple You cannot add, delete, or modify , in other words applend、pop、insert None of these functions can be used , Force the display :
Its advantage is that it can guarantee tuple Will not be tampered with later . You can still output and get the length according to the position . It is worth noting that , If it is a number as an element , Parentheses may be considered mathematical operators , So we can distinguish by adding a comma .(a=() It's an empty tuple)
chrters=('Pirates',"We",1)
print(chrters)
print(len(chrters))
print(chrters[-1])
chch=(1,)
print(chch)
Besides , If you put one list As tuple An element of , We can still modify list Internal elements (tuple Only the corresponding list It is the same. )
L = [
['Apple', 'Google', 'Microsoft'],
['Java', 'Python', 'Ruby', 'PHP'],
['Adam', 'Bart', 'Lisa']
]
# Print Apple:
print(L[0][0])
# Print Ruby:
print(L[1][2])
# hold Java become C++:
L[1].insert(0,"C++")
print(L[1])
conditional :
If sentence :
Note that the indentation , Add a colon at each step ."elif"
a=int(input("your age is:"))
if a<=0 or a>=125:
print("It is nonsense!")
elif a<=12:
print("you are a child")
elif a<=18:
print("you are a teenager")
else:
print("you are an adult")
Loop statement :
a=("Somalian",'Pirates',"We","!")
for aa in a:
if aa!='!':
print("Say",aa,"!")
i=1
while i<=4:
print("say i=",i)
i=i+1
Output is :
dict&set:
dict
The difference in list Establish one-to-one correspondence between ordinal numbers and elements ,dict( Full name dictionary) Is to use the key - value (key-value) Corresponding to the . comparison list,dict It takes more memory but calls faster , yes “ Trade space for time ” Purpose .key It is used for calling , Therefore, it cannot be variable , Can be a string (string)、 Numbers 、tuple But it can't be list.
dict={"Alice":'good','Bob':"Mif","Cindy":96}
print(dict["Alice"])
dict['David']='Howdy'
print(dict)
print(dict.get("Elsa"),"NOTHERE")
dict.pop("Bob")
print(dict)
Output is :
try key:
# key=[1,2]
# dict[key]=1
key=(1,2)
dict[key]=1
print(dict)
Cancelled ( Try to use list As key) Show :
The normal code shows :
Set:
function :
https://docs.python.org/3/library/functions.html#abs
Did a random number guessing game hey hey
It's still a very interesting clam
Make it better ……
def my_guessfor5():
n=input("in which edge: ")
if n.isdigit()==0:
print("Please enter an integer as edge!")
return
n=int(n)
k=random.randint(0,n)
t=input("How many times?: ")
if t.isdigit()==0:
print("Please enter an integer as times!")
return
t=int(t)
tt=0
pal=0
while tt<t:
pp=input("now guess!: ")
if pp.isdigit()==0:
print("Please enter an integer to guess!")
continue
pp=int(pp)
if pp<k:
print("It is too small.")
tt=tt+1
if pp>k:
print("It is too large.")
tt=tt+1
if pp==k:
print("Congratulations! You win after",tt+1,"times!")
return
if tt==t:
print("I am sorry, you lost.")
return
The output is ~
Let's do a little math
import math
def solvvve(a,b,c):
if not (isinstance(a,(int,float))*isinstance(b,(int,float))*isinstance(c,(int,float))):
print("Please enter numbers!")
return
a=float(a)
b=float(b)
c=float(c)
dd=math.sqrt(b*b-4*a*c)
x1=(-b+dd)/(2*a)
x2=(-b-dd)/(2*a)
return x1,x2
Change to a little math
def poww(x,n=2,b=0):
s=1
while n>0:
s=s*x
n=n-1
s=s+b
return s
Output it for fun
Be careful , In this case n=2 and b=0 All are default parameters ( If you don't need it, you can leave it unchanged ). The default parameter must be set to the invariant object ( Otherwise, for example list Things that are , If it is used at a certain time , After that, you may always remember the changed appearance ).
Volatile variables 、 Keyword parameters and named keyword parameters **highly important
Volatile variables
Normally , All the variables we input are certain ( For example, numbers are numbers , A string is a string )【 Required parameters and default parameters 】.
However , For the following procedure , If we only use number( instead of *number),
def calu(*number,**pw):
s=0
for num in number:
s=s+num
print("answer is",s,"the stu:",pw)
We need to use cal([1,2]) perhaps cal((1,2)) Input tuple、list Call function in the form of .( Otherwise it will show TypeError: calu() takes 1 positional argument but 2 were given) therefore , We want to use *number Instead of number, In this way, the program will turn the input lump into a tuple Lose it .( It can be used cal(*(1,2)) Keep using tuple perhaps list For input )
Keyword variables :
**pw, Enter a dict, You don't have to type in , The call form is as :
Name keyword parameters :
def pfff(x,n=2,*,name,clss):
s=1
while n>0:
s=s*x
n=n-1
print(s,",the student is",name,"in class",clss)
return
Output check Several times :
If you set the required parameters 、 Default parameters 、 Variable parameters 、 Name keyword parameters 、 Keyword parameters are written ( This order must be followed ), It can be :
def pfff(x,n=2,*numm,name,clss,**what):
s=1
while n>0:
s=s*x
n=n-1
for num in numm:
s=s+num
print(s,",the student is",name,"in class",clss,"others:",what)
return
Output it and try :
Teacher Liao's warm tips :
function :
Recursive function :
def mutli(n,m):
if m==1:
return n
else:
return n+multi(n,m-1)
def move(n,a,b,c):
if n == 1:
print(a, '-->', c)
if n>1:
move(n-1,a,c,b)
print(a, '-->', c)
move(n-1,b,a,c)
Advanced features
section :
L=list(range(100))
LL=L[::10]
LLL=L[:10:2]
LLLL=L[-10::5]
print("L=",L,"LL=",LL,"LLL=",LLL,"LLLL=",LLLL)
iteration :
L=("Who","lives","in","a","pinapple","under","the","sea")
for i in L:
print(i)
List generation :
import sympy
l=[y for y in range(100) if sympy.isprime(y)]
print(l)
import os
l=[d for d in os.listdir(".")]
print(l)
This for The function of looping to generate lists in just one line of code is really amazing . Try a classic example :
import numpy as np
L=np.random.randn(15)
l=[d for d in L if d>0]
ll=[d if d>0 else 0 for d in L]
print("L=",L,"\n l=",l,"\n ll=",ll)
among L It is a randomly generated one with 15 A list of elements , Its distribution conforms to 0 Is the central normal distribution .l Extract all of them greater than 0 The item ,ll It's a L Items smaller than zero are classified as 0.
generator :
# Generate the Fibonacci sequence - Circular Edition
nn=int(input("input:")) # Need to use int() Convert to number
def fibb(N):
i,a,b=1,1,1
while i<N:
a,b=b,a+b
i=i+1
yield a # Need to be in the loop yielda
return 'success!yohoho~'#'' Represents the output string
n=fibb(nn)
while True:
try:
t=next(n)
print("new:",t)
except StopIteration as e: #StopIteration Catch errors for output
print("output:",e.value)
break # It must be added, or it will be output all the time output
Output :
Yang hui triangle :
# Yang hui triangle : Output the parameters of each line
nn=int(input("input:"))
def yhsj(N):
yield [1]
n=2
a=[1,1]
while n<=N:
b=[1]
t=0
while t<n-2:
t=t+1# Together with n-2 Time
b.append(a[t-1]+a[t])
b.append(1)
a=b
n=n+1
yield a
return "END"
n=yhsj(nn)
while True:
try:
print("new:",next(n))
except StopIteration as e:
print("Output:",e.value)
break
Teacher Liao's class homework :
yield [1]
L=[1,1]
while True:
yield L
L=[L[i]+L[i+1] for i in range(len(L)-1)]#len([1,1])=2 range(2):0,1
L.append(1)
L.insert(0,1)
iterator :
First consider iterable、iteration:
Generators are Iterator
object , but list
、dict
、str
Although it is Iterable
, But not Iterator
.
hold list
、dict
、str
etc. Iterable
become Iterator
have access to iter()
function :
from collections.abc import Iterable, Iterator
#L=123 #False F TypeError: 'int' object is not iterable
#L=[123] #True F T
#L=(123,) #True F T\
L=(x*x for x in range(12)) #T T T
L=iter(L)
#print(isinstance(L,Iterable))
print(isinstance(L,Iterator))
边栏推荐
- MySQL on delete cascade [tutorial]
- 李宏毅2020机器学习深度学习笔记1+2 &&深度学习基础与实践课程笔记2
- 如何有效规避代码被“投毒”?
- Xilinx Mipi csi-2 receiver subsystem IP details
- FFMpeg WASAPI can't activate audio endpoint错误的处理
- 我想问下ODPS的建表ddl不能直接在mysql里执行,STRING类型不兼容,这个是只能自己调整吗
- In July, the "China database industry analysis report" was released! Be prepared for danger in times of safety, safety first
- hyperledger fabric1.0整体架构与记账逻辑架构的分析
- BGP相关知识点
- 李宏毅2020机器学习深度学习笔记2
猜你喜欢
随机推荐
SQL结果导出功能,工单点不进去,点了工单,一直是空白界面,没有响应,怎么办?
【2022华为开发者大赛系列直播】华为开发者大赛—乾坤云服务赛事解读
短信验证
AI 助力双碳目标:让每一度电都是我们优化的
Google Earth Engine ——neighborhoodToBands函数的使用
Debezium grabs data from Oracle to Kafka
使用系统自带SQLite
class, classloder, dex 详解
wine 微信初始化96%卡住
我想问下ODPS的建表ddl不能直接在mysql里执行,STRING类型不兼容,这个是只能自己调整吗
yaml编写规则以及YAML和JSON对比
如何有效规避代码被“投毒”?
influxdb查询时间戳问题
2021/7/24 SVM 2021/7/26 后门学习&对抗神经网络
Vite3.0都发布了,你还能卷得动吗(新特性一览)
MCU external interrupt trigger mode: description of level trigger and edge trigger
User experience | deeply cultivate user experience and build a moat for bank competition
李宏毅2020机器学习深度学习笔记2
对于IT互联网行业来说,家觉得学历重要还是能力?
半导体新晋独角兽,TCL刚刚投了18亿