0%

初探python语法
关键字 数据类型 常用函数 常用语法

虚拟python环境

  • 创建虚拟环境
    python -m venv venv
  • 激活虚拟环境
    source venv/bin/activate

#

编码默认UTF-8
# -*- codeing: cp-1252 -*- : 更改编码
标识符可为中文等非ASCII字符
关键字 :

1
2
3
import keyword
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  1. 单行注释
    #我是注释
  2. 多行注释
    1
    2
    """我是注释"""
    '''我是注释'''
  3. tab缩进与空行表示代码块或函数/方法
  4. 可以使用\来连接行,[]{}()中不用
  5. #!/usr/bin/env python3

数据类型

unmut : Number String Tuple
mut : List Dictionary Set

Number

运算: + - * **(乘方) /(float) //(向下取整,int)
(int)a
> < == and or not
所有非零数字和非空其他类型类型均被视为True

类型 定义 print 备注
bool a=True True True/False
int a=1 1
float a=1.12345 1.12345 double 8位
complex a=1+2j;a=complex(1,2) (1+2j) .real实部.imag虚部,均为float

String

运算: + * [ ] [ : ] [ : : ] r
字符串不可mut,不可str[x]='s'
in
not in
格式化为字符串
%c s d u o x X f
%e E g G p
格式化辅助指令

  1. *(*.*) 动态指定精度 print("%*d,%*.*f"%(iw,a,fwa,fwb,b))
    • 左对齐
    • 正数前+
  2. 正数前
  3. 8/16进制加0 0x 0X

  4. 0 数字前填充0
  5. %
  6. (var)
  7. m.n. 指定精度
  8. fstring : print(f"hello,{name}")
    • py>=3.8 : 可使用=拼接表达式与结果print(f"{1+2=}")# 1+2=3
类型 定义 print 备注
string str1=”str1”;
str2=’str2’;
str3=’’’str31
str32’’’;
str4=”””str41
str42”””;
str1
str2
str31
str32
str41
str42
+,*,\,r (raw string)
0…-1
str[头,尾,步长]

str[head:tail] [head,tail) 无论是使用正负标号,均为从前往后截取(step=1)
str[head:tail:step] [head,tail,step) step默认为1,设为-1表示逆向输出,相当于for循环

1
2
3
4
5
6
7
a='abcde'
print(a[1:2]) # b
print(a[1:]) # bcde
print(a[:3]) # abc
print(a[-4:-2]) # bc
print(a[-4:]) # bcde
print(a[:-2]) # abc

![[Pasted image 20231109171002.png]]

常用方法:

  • capitalize()

List

list=[1,2.9,"hello",["hello","world"],(1,2,3)]

运算: + * [ ] [ : ] [ : : ]
List可变
list[x]='x'
list[x:y]='x'
list[start:tail:step]
max min len list

Tuple

Tuple=(1,1.1,"hello",["hello"],(1,2),(),(1,))

相当于unmut List
* + …
构造元素个数为0的Tuple Tuple=()
构造元素个数为1的Tuple Tuple=(1,)
Tuple不可变,但可包含可变的类型如List,可以修改List[]
max min len tuple

string,list,tuple都属于序列(sequence)

Set

Set={1,2,3.2,"n",("Tuple")}

无序,可变,内部元素必须Hashable,List,Set均不可Hash,重复元素将被自动过滤
运算: - 差集 | 并集 & 交集 ^ 不同时存在的(对称差集/异或)
空Set必须用set()创建,{}表示空Dictionary

Dictionary

Dictionary={1:"hello","1":"one","2":["two","two"],"3":("three")}
Dictionary[4]="world"
Dictionary["4"]=("world")
print(Dictionary.keys()) # dict_keys=([1, ‘1’, ‘2’, ‘3’])
print(Dictionary.values()) # dict_values([‘hello’, ‘one’, [‘two’, ‘two’], ‘three’]
使用dict构造
Dictionary=dict([(1,"one"),(2,"two")])
使用推导式
Dictionary={x:x**3 for x in [2,3,4,5]}
Dictionary={x:x**3 for x in (2,3,4,5)}
Dictionary={y:y**3 for y in (2,3,4,5)}

  • *
    len str dict

bytes

by=b'hello

切片 + *

类型转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int(x[,base]) # base用于将字符串转换为Int时指定进制 
float(x)
complex(real[,imag])
str(x[,base]) # base用于将Int转换为字符串时指定进制
repr(x) # 返回对象 x 的“官方”表示形式,通常是一个字符串,通常是一个有效的Python表达式,通过使用它,你可以得到一个字符串,可以用来重新创建对象 x,以便于调试和代码中的重现,通常只用于调试
tuple(x)
list(x)
set(x)
dict(d)
frozenset(s) # 转换为不可变set
chr(x) # int=>ch
ord(x) # ch=>int
hex(x) # int=>hex
oct(x) # int=>oct

运算符

算术运算符

+ - * ** / // %

比较运算符

== != > < >=<=

赋值运算符

= += -= *= **= /= //= %=
:= python>=3.8
除了:=外的赋值运算符不返回赋值结果

位运算符

& | ~ ^ << >>

逻辑运算符

and or not

成员运算符

in
not in
判断成员是否在指定list,set…中

身份运算符

is 类似 id(x)==id(y)
is not类似 id(x)!=id(y)

常用函数/语法

  1. 类型判断 type: 认为子类非父类,isinstance认为子类是父类
    1
    2
    3
    4
    5
    6
    7
    8
    print(type(a))
    '''
    <class 'int'>
    <class 'float'>
    <class 'complex'>
    <class 'str'>
    '''
    if isinstance(a,int): ...
  2. input
    1
    in=input("我是提示")
  3. print
    1
    2
    3
    4
    5
    6
    7
    print(a,b,c)
    #print默认换行(3.0+),使用
    print(var,end='')
    print(var,end=' ')
    print(var,end="")
    print(var,end=" ")
    #禁用换行
  4. import 与from … import …
    1
    2
    3
    4
    import sys # sys.stdout. ; sys.stdout. 
    from sys import stdout # stdout.
    from sys import stdout , stdin # stdout. ; stdin.
    from sys import * # stdin. ; stdout.
  5. del 删除变量
    del var1[,var2[,var3[....,varN]]]
  6. 赋值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    a=1
    a,b=1,"a"
    class ExampleClass:
    pass

    # 创建一个对象
    obj = ExampleClass()

    # 使用 id() 函数获取对象的唯一标识符
    obj_id = id(obj)

    # 使用 %p 格式说明符格式化指针值
    formatted_str = "Object address: %p" % obj_id

    print(formatted_str)
  7. ord 将字符转换为数字
  8. format(x[,format])
  9. pass 空语句
  10. dir(modulename) 显示模块内定义的所有名称 , 返回List
  11. 包的结构
    1
    2
    3
    4
    5
    6
    7
    8
    9
    .
    ├── __init__.py
    ├── sub_effects
    │   ├── __init__.py
    │   └── surround.py
    └── sub_formats
    ├── __init__.py
    ├── jpg.py
    └── png.py
    包内,变量__all__应当包含所有可被import的内容,在from pkgname import *时被使用

常用库函数

1
2
sys.stdout.write(string) # 
sys.stdout.write("hello") # hello5

语句/语法

条件分支循环

1
2
3
4
5
6
7
if condition1:
...
elif condition2:
...
else
...

1
2
3
4
5
6
7
8
match subject:
case 1:
...
case 2|3|4:
...
case _:
...

1
2
while condition:

1
2
3
4
5
while condition:
...
else:
...

1
while True : ...
1
2
3
4
for <var> in <seq> : 
...
else:
...

推导式 List Set Tuple Dictionary

expression for <var> in <seq> if <condition>
结果值1 if 判断条件 else 结果2 for 变量名 in 原列表

迭代器与生成器

it=iter()
next(it)
含有yield的函数为生成器函数

函数

定义函数

1
2
3
4
5
<!-- # 函数说明 -->
def function(a,b):
...
return 1 # 无return则返回None

参数与调用时参数

1
2
3
4
5
6
7
8
def function(a,b,c=100): # 默认参数必须在末尾
...
return 1 # 无return则返回None

function(1,2)
function(1,2,3)
function(b=1,a=2)
function(b=1,a=2,c=3)

不定长参数
def functionname([formal_args,] *var_args_tuple ):

  1. *arg Tuple
    1
    2
    3
    4
    5
    6
    7
    def function(arg1,*arg2):
    print(arg1)
    print(arg2)

    function(100,"hello","world")
    #100
    #('hello', 'world')
  2. *arg Dictionary
    1
    2
    3
    4
    5
    6
    7
    8
    def function(arg1,**arg2):
    print(arg1)
    print(arg2)

    function(100, a="hello",b="world")
    # function(arg1,arg2name=arg2value,arg3name=arg3value)
    #100
    #('hello', 'world')

lambda表达式

lambda [arg1 [,arg2,.....argn]]:expression
lambda [arg1 [,arg2,.....argn]]:expression[,[arg1[,arg2,...argn]]]

* 与/

1
2
3
def function(a,b,/,c,d,*,e,f):
...

a,b不得使用关键字参数
e,f必须使用关键字参数
Tips: 关键字参数后不得使用位置参数

  • 构造函数__init__()
  • next函数__next__()
  • raise StopIteration