Pass teacher Liao Xuefeng's series of courses quickly 1

Posted by BadgerC82 on Mon, 03 Jan 2022 20:05:26 +0100

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

From July 27, 2021 as soon as possible

catalogue

overview:

About coding method:

Python Basics:

List&Tuple:

List

tuple

Condition judgment:

If statement:

Loop statement:

 dict&set:

dict

Set:

Variable variables, keyword parameters, and named keyword parameters * * highly important

Variable variable

Keyword variable:

Named keyword parameters:

Function:

Recursive function:

Advanced features

section:

Iteration:

List generation:

Generator:

Iterator:

overview:

The advantage of python lies in its perfect basic code base. The disadvantage is that it runs slowly (compared with C) (but it doesn't actually affect it)

win+R → cmd Enter → python (flag is > > >)

exit() exit

If you use VS code, you need to switch directories

Then the input and output: (double quotation marks and single quotation marks can be used to represent strings)

When running from the command line:

python starts comments with "#" and expresses the format in indentation (therefore, the indentation should be checked after copying and pasting). It is case sensitive and the 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 method:

ASCII coding (upper and lower case letters + numbers) → countries join their own language characters (China: GB2312) → Unicode (usually two bytes) is formed internationally → UTF-8 is generated for simplification (the number of bytes is different, one English letter, three Chinese characters and some four)

In the computer memory, Unicode coding is used uniformly. When it needs to be saved to the hard disk or transmitted, it is converted to UTF-8 coding.

When editing with Notepad, UTF-8 characters read from the file are converted into Unicode characters and stored in memory. After editing, Unicode is converted into UTF-8 and saved to the file when saving.

When browsing a web page, the server will convert the dynamically generated Unicode content into UTF-8 and then transmit it to the browser, so you can see information similar to < meta charset = "UTF-8" / > on the source code of many web pages, indicating that the web page is encoded in UTF-8.

print(ord('Ha'))
print(chr(123456))

Python Basics:

List&Tuple:

List

Is the most commonly used variable form. The elements can be strings, numbers, Boolean values, 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 operation result is:

tuple

Compared with list, tuple cannot be added, deleted or modified, that is, applend, pop and insert functions cannot be used, and forced to display:

Its advantage is that it can ensure that the 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 regarded as mathematical operators, so we can distinguish them by adding a comma. (a = () is an empty tuple)

chrters=('Pirates',"We",1)
print(chrters)
print(len(chrters))
print(chrters[-1])
chch=(1,)
print(chch)

In addition, if we take a list as an element of a tuple, we can still modify the elements inside the list (tuple only ensures that the corresponding list is unchanged)

L = [
    ['Apple', 'Google', 'Microsoft'],
    ['Java', 'Python', 'Ruby', 'PHP'],
    ['Adam', 'Bart', 'Lisa']
]
# Print Apple:
print(L[0][0])
# Print Ruby:
print(L[1][2])
# Turn Java into C + +:
L[1].insert(0,"C++")
print(L[1])

Condition judgment:

If statement:

Pay attention to indentation and 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

Unlike list, which establishes one-to-one correspondence between ordinal numbers and elements, Dict (full name dictionary) uses key value correspondence to store elements. Compared with list, dict takes up more memory but calls faster. It is the purpose of "exchanging space for time". Key is used for calling, so it cannot be variable. It can be string, number, tuple, but not 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)

Logged out (try to use list as key) displays:

Normal code display:

Set:

 

Function:

https://docs.python.org/3/library/functions.html#abs

Did a random number guessing game hey hey

It's still a fun clam

Further improvement

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

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 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 to play

Note that both n=2 and b=0 are default parameters at this time (you can not modify them if you don't need them). The default parameters must be set as unchanged objects (otherwise, if you use something such as list, you may remember the changed appearance after one time).

Variable variables, keyword parameters, and named keyword parameters * * highly important

Variable variable

Normally, the variables we input are certain (for example, numbers are numbers and strings are strings) [required parameters and default parameters].

However, for the following program, 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 call the function by entering tuple and list in cal([1,2]) or cal((1,2)). (otherwise, typeerror: calu() takes 1 positive argument but 2 were given) therefore, we thought of using * number instead of number, so the program will change the input lump into a tuple by default. (you can use cal(*(1,2)) to continue using tuple or list as input)

Keyword variable:

**pw, enter a dict, which can be left blank. The call form is as follows:

Named 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 the required parameters, default parameters, variable parameters, named keyword parameters and keyword parameters are written (in this order), they 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 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)

The function of this for loop to generate a list 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)

Where l is a randomly generated list with 15 elements, and its distribution conforms to the normal distribution centered on 0. L extracts all items greater than 0, and ll classifies all items less than zero in L to 0

 

Generator:

#Generate Fibonacci sequence - circular version
nn=int(input("input:")) #You need to convert it to a number with int()
def fibb(N):
    i,a,b=1,1,1
    while i<N:
        a,b=b,a+b
        i=i+1
        yield a #You need to yield in the loop
    return 'success!yohoho~'#'' represents the output string
n=fibb(nn)
while True:
    try:
        t=next(n)
        print("new:",t)
    except StopIteration as e: #StopIteration captures errors for output
        print("output:",e.value)
        break #Must be added, otherwise output will always be 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#n-2 times in total
            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 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:

Consider iterable and iteration first:

Generators are Iterator objects, but list, dict and str are iteratable, but not Iterator.

To change list, dict, str, etc. into Iterator, you can use the 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))