Summary of Python self-study process knowledge points

Learning objectives

First of all, why learn python?

  1. I don't want to be a full stack programmer. It's not cool girl. java and C are difficult. I returned them to the teacher half a year after graduation. Basic python is relatively simple (I don't mean simple python!! advanced python will talk about it later);
  2. Install x;
  3. Convenient for life, because python is really easy to use.

There is only motivation when there is a goal!

Goal: learn basic python and crawler. You can climb down a novel or poem on Baidu.

Install Python

Python Download
cmd executes python to check whether the installation is successful. If the version number appears, the installation is successful.

Python Basics

I followed teacher Liao Xuefeng's tutorial, Python tutorial by Liao Xuefeng.
VSCode create 0322 Py file.
cmd. Found 0322 Directory of python, Python 0322 Py executes code.

Input and output

# output
print("hello python")
# input
name = input("please enter your name:")
print("name:", name)

data type

Integer, floating point number, string, Boolean value (True, False), null value (None), variable (variable name must be a combination of upper and lower case English, number and and cannot start with a number), constant (in Python, constant is usually represented by variable name in all uppercase)

# r '' indicates that the escape character is not escaped
print(r"///demo")
# '''...''' Represents multiline content
print('''lizi
 yes
 Cutie''')

# Boolean judgment
print(5 > 3)

# division
print("/", 10/3)
# Floor division and rounding
print("//", 10//3)
# Surplus
print("%", 10%3)

Method, placeholder

print("abcde Length of", len('abcde'))
# Length of abcde 5
print("hello, %s" %"world")
# hello, world
placeholder replace content
%dinteger
%fFloating point number
%scharacter string
%xHexadecimal integer
print('%.2f%%' % 24.2455)
# 24.25%

list

List

Built in data type
Element types can be different or nested, such as: ["apple", "orange", "sweets", 2, [True, "22"]]

food = ["apple", "orange", "sweets"]
print("list Length of", len(food))
# Length of list 3
print("list First, second, penultimate element", food[0], food[1], food[-1])
# The first, second and penultimate elements of the list are apple orange sweets
# Insert element append() at the end
food.append("banana")
print(food)
# ['apple', 'orange', 'sweets', 'banana']
# Insert element at specified position ()
food.insert(2, "bread")
print(food)
# ['apple', 'orange', 'bread', 'sweets', 'banana']
# Delete last element pop()
print(food.pop())
print(food)
# banana
# ['apple', 'orange', 'bread', 'sweets']
# Delete the specified location element pop(i)
print(food.pop(1))
print(food)
# orange
# ['apple', 'bread', 'sweets']
# Element replacement
food[0] = "peach"
print(food)
# ['peach', 'bread', 'sweets']

tuple

tuple has no methods such as append(), insert(), pop(). Once defined, it cannot be changed.
When there is only one element, omit the parentheses, not tuple type. You can add a comma to represent the tuple type.

people = ("Liz", "Andy", "Bob")
print(people)
# ('Liz', 'Andy', 'Bob')
test = ("Jim")
print(test)
# Jim
test2 = ("Jim", )
print(test2)
# ('Jim',)

Conditional judgment

Use if...: else:...

height = 24
if height > 30:
    print("1")
elif height > 5:
    print("2")
else:
    print("3")
# 2

# As long as x is a non-zero value, non empty string, non empty list, etc., it is judged to be True, otherwise it is False.
if x:
    print('True')
# input
input()
# Convert string to integer
int()

loop

for... in loop

food = ["apple", "nut", "coke"]
for item in food:
    print(item)
# apple
# nut
# coke

# Integer sequence of 0-num
range(num)

while Loop

num = 2
all = 3
while all > 0:
    num = num * num
    all = all - 1
print(num)
# 256

Break break loop

num = 2
all = 3
while all > 0:
    num = num * num
    all = all - 1
    if all < 2:
    	break
print(num)
# 16

continue skip loop

n = 0
while n < 5:
    n = n + 1
    if n%2 == 0:
    	continue
    print(n)
# 1
# 3
# 5

dict and set

dict

The full name of dict is dictionary, which is the same as map. It uses key value storage to find information easily and quickly.

info = {"name": "Liz", "age": "18", "weight": "44kg"}
print(info["name"])
# Liz
info["height"] = "160cm"
print(info)
# {'name': 'Liz', 'age': '18', 'weight': '44kg', 'height': '160cm'}
print(info.get("height"))
# 160cm
print(info.pop("name"))
# Liz
print(info)
# {'age': '18', 'weight': '44kg', 'height': '160cm'}

set

A set of key s, but does not store value. Elements cannot be repeated.

s = set([1, 2, 3, 2])
print(s)
# {1, 2, 3}
s.add(4)
s.remove(1)
print(s)
# {2, 3, 4}
a = set([1, 2, 5])
print(a & s)
# {2}
print(a | s)
# {1, 2, 3, 4, 5}

function

python built-in method

# python built-in function, abs(), to find the absolute value
print(abs(-10))
# 10

Custom function: in Python, define a function using def statement, write out the function name, parentheses, parameters in parentheses and colons in turn, then write the function body in the indented block, and the return value of the function is returned by return statement.

def my_abs(x):
# isinstance() type error
	if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x
print(my_abs(-2))
# 2
# Empty function pass, function placeholder
if a > 10:
	pass

parameter

Location parameters

def power(x, n):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
print(power(5, 2))
# 25

Default parameters

The required parameter is in the front, and the default parameter is in the back.
The default parameter must point to an invariant object

def power(x, n=2):
    s = 1
    while n > 0:
        n = n - 1
        s = s * x
    return s
print(power(5))
# 25

Variable parameter

def calc(*numbers):
    sum = 0
    for x in numbers:
        sum = sum + x*x
    return sum
print(calc(1, 2, 3))
# 14
nums = [1, 2, 3]
print(calc(*nums))
# 14

Keyword parameters

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
print(person("Liz", 18))
# name: Liz age: 18 other: {}
# None
extra = {'city': 'Beijing', 'job': 'Engineer'}
print(person('Jack', 24, **extra))
# name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
# None

Named keyword parameter

The parameters after the separator * are named keyword parameters

def person(name, age, *, city, job):
    print(name, age, city, job)
person('Jack', 24, city='Beijing', job='Engineer')
# Jack 24 Beijing Engineer

The order of number definition must be: required parameter, default parameter, variable parameter, named keyword parameter and keyword parameter

def f1(a, b, c=0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
f1(1, 2, 3, 'a', 'b', x=99)
# a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}

Recursive function

recursion

Calculate 1x2x3x4x...... n

def fact(n):
    if n == 1:
        return 1
    return n * fact(n-1)
print(fact(3))
# 6

Tail recursion

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)
print(fact(3))
# 6

Advanced features

section

Take the object n-m, Obj[n:m:l] (excluding m, one for each L), which can be omitted when n=0.

people = ["Andy", "Lily", "Popi", "Uu", "Wendy"]
print(people[:4:2])
# ['Andy', 'Popi']

food = ("apple", "nuts", "banana", "strawberry", "chicken")
print(food[:3])
# ('apple', 'nuts', 'banana')

print("asdfghjkl"[::2])
# adgjl

Iteration

Use for in... Loop iteration, the content of in needs to judge whether it is a loop iteration.

from collections.abc import Iterable
print(isinstance('asdf', Iterable))
# True

List generation

If before for Else is an expression, while if after for is a filter condition, and else cannot be taken.

# Generate 1-4
print(list(range(1, 5)))
# [1, 2, 3, 4]

# Generate 1 * 1-4 * 4
print(list(i*i for i in range(1,5)))
# [1, 4, 9, 16]

# Lowercase, remove non string
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [x.lower() for x in L1 if isinstance(x, str)]
# ['hello', 'world', 'apple']

Generator generator

The mechanism of calculating while looping. There are the following ways to generate a generator:

  1. Change [] of list generation formula to ()
g = (x * x for x in range(3))
print(g)
print(next(g))
# <generator object <genexpr> at 0x000001BD81FC1270>
# 0
for i in g:
    print(i)
# 0
# 1
# 4
  1. A function definition contains the yield keyword

Functional programming

function

The variable of a function can be a function, and the return can also be a function.

def add(x, y, f):
    return f(x) + f(y)
print(add(-5, 6, abs))
# 11

map

map (conversion rule, parameters to be converted)

def fn(x):
    return x*x
print(list(map(fn, [1, 2, 3, 4])))
# [1, 4, 9, 16]
print(list(map(str, [1, 2, 3, 4])))
# ['1', '2', '3', '4']

reduce

from functools import reduce
def add(x, y):
    return x + y
print(reduce(add, [1, 2, 3, 4]))
# 10

sorted()

Sorted (object, rule formulated by key function, reverse=True), key rule, can be omitted, reverse=True, reverse sort, can be omitted

print(sorted([36, 5, -12, 9, -21], key=abs))
# [5, 9, -12, -21, 36]

Return function

def calc_sum(*args):
    def sum():
        n = 0
        for i in args:
            n = n + i
        return n
    return sum
f = calc_sum(1, 2, 3, 4)
print(f)
# <function calc_sum.<locals>.sum at 0x0000018038F1E160>
print(f())
# 10

To form a closure, note: the return function should not reference any cyclic variables or variables that will change later.

lambda anonymous function

lambda parameter of anonymous function: the return value # has no return and no name. Don't worry about function name conflict.

f = lambda x: x * x
print(f)
# <function <lambda> at 0x000001BF94BFE0D0>
print(f(5))
# 25

Decorator

def fn():
    print('fn ah')
fn()
# fn
print(fn.__name__) # Function__ name__ Property and get the name of the function
# fn

# Define a decorator for printing logs
def log(func):
    def wrapper(*args, **kw):
        print('call %s():' % func.__name__)
        return func(*args, **kw)
    return wrapper
@log
def fn():
    print('fn ah')
fn()
# call fn():
# fn

Climb the bean net chestnut

https://github.com/ChestnutNeko/pythonStudy/blob/main/douban.py

Keywords: Python

Added by rsmith on Thu, 27 Jan 2022 19:33:26 +0200