python tutorial (continuously updated)

The picture is missing

python learning path

img

variable name

• The variable name must start with a letter or an underscore, and the middle of the name can only be composed of letters, numbers and an underscore "_". • Variable names cannot exceed 255 characters in length.
• Variable names must be unique within the valid scope.
• Variable names cannot be keywords in Python.
Variable names are case sensitive

The keywords of python are
insert image description here

type of data

data type conversion

View data type: use type()

int(x [,base ]) converts x to an integer

float(x) converts x to a floating point number

complex(real [,imag ]) creates a complex number

chr(x) converts an integer to a character

ord(x) converts a character to its integer value

hex(x) converts an integer to a hexadecimal string

oct(x) converts an integer to an octal string

bin(x) converts an integer to a binary string

Tuple and list conversion

str = 'hello world' 
print(list(str)) 
print(tuple(str)) 
tup = ('hello','world') 
print(list(tup)) l
ist = ['hello','world'] 
print(tuple(list))

convert to dictionary

li = ['name', 'age', 'city'] 
tup = ('jmilk', 23, 'BJ') 
kvtup = zip(li, tup) 
print(kvtup) print(dict(kvtup))

out:[('name', 'jmilk'), ('age', 23), ('city', 'BJ')] 
  {
    
    'city': 'BJ', 'age': 23, 'name': 'jmilk'}

string

Basic operations on strings

#字符串拼接
'a'+'b'
-----
ab

#复刻
'a'*2
-----
aa

#字符串查找
#字符串查找是指查找某一个字符串是否包含在另一个字符串中
#用in或者not in两种方法都可以,还可以用find()方法
'ab' in 'abc'
-----
True

'abc'.find('c')
--------
2

'abc'.find('d')
------
-1

#如歌不存在那就返回-1


#字符串索引
a[0]#从零开始

#字符串分割
"a,b,c".split(',')#将字符串用逗号分隔,列表展示
"a|b|c".split('|')#将字符串用|分隔,列表展示

#字符串删除
" A ".strip()#删除空格
"\ta\t ".strip()#移除换行符
'aAa'.strip('a')#移除a

Escape characters: \n newline, etc.

Operation characters +, *, [], [:], in, not in, r'\n' (raw string), %s (output of formatted string)

Format character: %s format string

the list

# 列表合并
#有两种方法,一种是+,另一种是extend
list1=[1,2,3]
list2=[4,5,6]
list1+list2
---------
[1,2,3,4,5,6]

list1.extend(list2)
[1,2,3,4,5,6]

list2.extend(list1)
[4,5,6,1,2,3]

#将列表B合并到列表A中,用到的方法是A.extend(B);将列表A
#合并到列表B中,用到的方法是B.extend(A)。

#列表插入
#主要有append()和insert()两种方法
#append()是在列表末尾插入新的数据元素
list1.append('a')
-----------
[1,2,3,'a']

insert()是在列表的指定位置插入新的数据元素。

list1.insert(1,'a')#在第2个位置插入a
----------
[1,'a',2,3]

# count用法
某值在列表中出现的次数
list1=[1,2,3,3,4,4]
list1.count(3)
-------
2

# index 获取某值的位置
list1.index(2)
---------
1
如果不止一个那么会返回第一个所在的位置

#列表索引
索引分为单个索引与切片索引
索引都是从0开始的
list1[0]#第一个位置
list1[1,3]#第二个到第三个,不包含第四位
list1[2:]#第三位到最后一位

#删除
pop和remove两种用法
pop指定的位置删除
remove指定元素删除

list1.pop(2)
list1.remove("a")

#排序
sort()
list1.sort()#默认升序

dictionary

A dictionary is a key-value pair structure

# 创建字典
dict1={
    
    }
dict1['a']=123
dict1['b']=456
--------
{
    
    "a":123,"b":456}

#用列表的方式放在元组中,用dict进行转化
content=(['a','1'],['b','1'])
dict2=dic(content)
dict2
-----
{
    
    "a":"2","b":"2"}
#keys,values和items用法
dict2.keys()
dict2.values()
dict2.items()

tuple

Tuples cannot be modified, and tuples use parentheses

获取元组长度
tup=(1,2,3)
len(tup)

#获取元组元素可以用索引或者切片索引的方式
不再赘述

#元组列表相互转化
list(tup)
tuple(list)

The zip() function takes an iterable object (list, tuple) as a parameter, packs the corresponding elements in the object into tuples, and then returns a list composed of these tuples. Often used with a for loop.

list1=[1,2,3,4]
tup2=(5,6,7,8)
for i in zip(list1,tup2):
    print(i)

insert image description here

str. format () usage

string format

print("{} {}".format("hello", "world")) # 不设置指定位置,按默认顺序 
print("{0} {1}".format("hello", "world")) # 设置指定位置 
print("{1} {0} {1}".format("hello", "world")) # 设置指定位置 # 设置参数 print("网站名:{name}, 地址 {url}".format(name="百度", url="www.baidu.com")) # 通过字典设置参数
site = {
    
    "name": "百度", "url": "www.baidu.com"} 
print("网站名:{name}, 地址 {url}".format(**site)) # 通过列表索引设置参数 my_list = ['百度', 'www.baidu.com'] 
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是可选的

format number

The following table shows the various ways str.format() formats numbers:

Number Format Output Description

Floating point setting
. 2f means to display in floating point, and the output retains two digits after the decimal point, where the number 2 represents the number of decimal places reserved after the output

print("{:.2f}".format(2))

A percentage setting of
2% means that it is displayed in the form of a percentage, and the output retains two decimal places, where the number 2 represents the number of decimal places reserved after the output

print("{:.2f%}".format(0.002))

Format

Indentation: use the tab key, if you want to cancel the indentation, use the shift+tab key
Note: # single-line indentation, ''' multi-line indentation''',""" multi-line indentation 2 """

operator

Arithmetic operators
insert image description here
Comparison operators
insert image description here

Logical Operators
insert image description here

Loop Statements vs. Conditional Statements

for
while
if

function

define call function function

def a(canshu):
	"""
	函数指定注释:过滤危险字段 可以用a.__doc__,help(a)
	"""
	import re
	pattern=r'(黑客抓包)
	sub=re.sub(pattern,'@_@',string)
	print(sub)
	
#调用函数
a("abcderf")

parameter

Formal parameters (formal parameters): parameters in the function definition parameter list

Actual parameters (actual parameters): the parameters passed in when the function is called

Position parameters: the first must have the same number, and the second must have the same position, otherwise an exception message of typeerror will be thrown

Keyword parameters: Use the name of the formal parameter to specify the key value, which does not need to be exactly the same as the position of the formal parameter

Parameter default value: If no parameter is specified, an exception will be thrown. When defining a function, specify the default value of the formal parameter directly. When there is no parameter, directly use the default value set when defining the function. The parameter that specifies the default form must be included in all parameters after, else a syntax error is generated

variable parameters :

The first form is *parameter, which means to accept any number of actual parameters and place them in the tuple.

The second form is **parameter, which means accepting any number of parameters similar to keyword parameter assignments

Return value : If there is no return function using the return function, it returns none by default, that is, an empty value, and multiple values ​​can be returned

def a(b,c):#b为形参
	print(b)
	
#调用
a(d,e)#d,e为实参

a(b=d,c=e)#关键字参数

#参数默认值
def a(b,c,d='2020'):
	pass
#查看默认值
a.__defaults__

#可变参数
def coffer(*coffername):
	for item in coffername:
		print(item)
#调用1
coffer('蓝山','卡布奇诺','摩卡')
#调用2
coffers=['蓝山','卡布奇诺','摩卡']
coffer(*coffers)

def coffer(**coffername):
	for key,value in coffername.items():#遍历字典
		print("["+key+"]喜欢的咖啡是:"+value)#输出组合后的信息
  return key,value
#调用1
coffer(a='蓝山',b='卡布奇诺')
#调用2
coffers={
    
    'a':'蓝山','b':'卡布奇诺'}
coffer(**coffers)

#返回值
cof=coffer(a='蓝山',b='卡布奇诺')
print(cof[0],cof[2])

Variable scope : Local variables refer to variables defined and used inside the function, otherwise a nameerror will be thrown

Global variables can act on variables inside and outside the function. There are two types. One is defined outside the function. After the variables inside the function are copied, they do not need to affect the variables outside the function.

The other is defined inside the function, using global to convert the local variable into a global variable, which can be accessed outside the function and modified inside the function.

#局部变量
def demo(): 
  name='abcd'
  print('局部变量为:',name)
demo()
print(abcd)
#nameerror报错

#全局变量
name='abcd'
def demo(): 
  print('全局变量为:',name)
demo()
print(abcd)

#第二种
name='abcd'
print('全局变量为:',name)
def demo(): 
  global name
  name='efgh'
  print('全局变量为:',name)
demo()
print(abcd)

anonymous function

Refers to a function lambda without a name, a lambda is an expression without a function body

lambda arg1, arg2, arg3...:expression
arg1, arg2, arg3 represent specific parameters, and expression represents
the operation to be performed by the parameter.

The simplest lambda function is
lambda x,y:x+y

advanced features

list generation

list1=[1,2,3,4]
[i**2 for i in list1]
--------
[1, 4, 9, 16]

list2=[5,6,7,8]
[i+j for i in list1 for j in list2]
-------
[6, 7, 8, 9, 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12]

The expression form of the map() function is map(function,agrs), which means to
perform a function operation on each value in the sequence args, and finally obtain a result sequence

a=map(lambda x,y:x+y,[1,2],[3,4])
a
-------
<map at 0x109fe3c4d00>

The result sequence generated by the map() function will not directly display all the results. To
obtain the results, you need to use the for loop to traverse. You can also use the list() method to
generate a list of the resulting values.

for i in a:
	print(i)
--------
4
6

#或者
list(map(lambda x,y:x+y,[1,2],[3,4]))
-----
[4,6]

object-oriented programming

Object: The abstract concept is any thing that exists. It can be divided into two parts, the static part and the dynamic part. The static part is called the attribute, and the dynamic part refers to the behavior of the object, that is, the execution action of the object

A class is a carrier that encapsulates the attributes and behaviors of an object. It can be said that a class of entities with the same attributes and behaviors is called a class.

Features of Object-Oriented Design Encapsulation, Inheritance, Polymorphism

kind

#创建类
class Name:#一般使用大些字母开头,驼峰式命名法
  """类的帮助信息""" 
  pass #类的实体

#创建类的实例,即实例化该类的对象
name=Name()
print(name)
#创建__init__方法:每当创建一个新的实例时,都会自动运行它,必须包含self属性和方法,用于访问类的属性和方法
class Name:
  """大雁名字"""
  def __init__(self,a,b,c):#构造方法
    print('我的名字是')
    print(a,b,c)
a='a'
b='b'
c='c'
name=Name(a,b,c)#创建类的实例

Define a function in a class: access through the instance name and dot of the class

#语法格式
def functionname(self,para):#必须有self存在,para各个参数间用逗号隔开
  bolck#方法体实现具体的功能
  
class Name:
  """大雁名字"""
  def __init__(self,a,b,c):#构造方法
    print('我的名字是')
    print(a,b,c)
  def fly(self,state):
    print(state)
a='a'
b='b'
c='c'
name=Name(a,b,c)#创建类的实例
name.fly('hhhh')#调用方法

Create properties in the class and access

Refers to the variables defined in the class, that is, attributes, which can be divided into class attributes and instance attributes according to the definition location

Guess you like

Origin blog.csdn.net/weixin_41867184/article/details/125343379