初探python语法
关键字 数据类型 常用函数 常用语法
虚拟python环境
- 创建虚拟环境
python -m venv venv - 激活虚拟环境
source venv/bin/activate
#
编码默认UTF-8
# -*- codeing: cp-1252 -*- : 更改编码
标识符可为中文等非ASCII字符
关键字 :
1 | import keyword |
- 单行注释
#我是注释 - 多行注释
1
2"""我是注释"""
'''我是注释''' tab缩进与空行表示代码块或函数/方法- 可以使用
\来连接行,[]{}()中不用 - #!/usr/bin/env python3
数据类型
unmut : Number String Tuple
mut : List Dictionary Set
Number
运算: + - * **(乘方) /(float) //(向下取整,int)
(int)a
> < == and or not
所有非零数字和非空其他类型类型均被视为True
| 类型 | 定义 | 备注 | |
|---|---|---|---|
| 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
格式化辅助指令
- *(*.*) 动态指定精度
print("%*d,%*.*f"%(iw,a,fwa,fwb,b)) - 左对齐
- 正数前
+
- 正数前
正数前8/16进制加0 0x 0X
- 0 数字前填充0
- %
- (var)
- m.n. 指定精度
- fstring :
print(f"hello,{name}")- py>=3.8 : 可使用=拼接表达式与结果
print(f"{1+2=}")# 1+2=3
- py>=3.8 : 可使用=拼接表达式与结果
| 类型 | 定义 | 备注 | |
|---|---|---|---|
| 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 | a='abcde' |
![[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 | int(x[,base]) # base用于将字符串转换为Int时指定进制 |
运算符
算术运算符
+ - * ** / // %
比较运算符
== != > < >=<=
赋值运算符
= += -= *= **= /= //= %=:=python>=3.8
除了:=外的赋值运算符不返回赋值结果
位运算符
& | ~ ^ << >>
逻辑运算符
and or not
成员运算符
innot in
判断成员是否在指定list,set…中
身份运算符
is类似id(x)==id(y)is not类似id(x)!=id(y)
常用函数/语法
- 类型判断 type: 认为子类非父类,isinstance认为子类是父类
1
2
3
4
5
6
7
8print(type(a))
'''
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
'''
if isinstance(a,int): ... - input
1
in=input("我是提示")
- print
1
2
3
4
5
6
7print(a,b,c)
#print默认换行(3.0+),使用
print(var,end='')
print(var,end=' ')
print(var,end="")
print(var,end=" ")
#禁用换行 - import 与from … import …
1
2
3
4import sys # sys.stdout. ; sys.stdout.
from sys import stdout # stdout.
from sys import stdout , stdin # stdout. ; stdin.
from sys import * # stdin. ; stdout. - del 删除变量
del var1[,var2[,var3[....,varN]]] - 赋值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15a=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) - ord 将字符转换为数字
format(x[,format])- pass 空语句
- dir(modulename) 显示模块内定义的所有名称 , 返回List
- 包的结构包内,变量
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 | sys.stdout.write(string) # |
语句/语法
条件分支循环
1 | if condition1: |
1 | match subject: |
1 | while condition: |
1 | while condition: |
1 | while True : ... |
1 | for <var> in <seq> : |
推导式 List Set Tuple Dictionary
expression for <var> in <seq> if <condition>结果值1 if 判断条件 else 结果2 for 变量名 in 原列表
迭代器与生成器
it=iter()
next(it)
含有yield的函数为生成器函数
函数
定义函数
1 | <!-- # 函数说明 --> |
参数与调用时参数
1 | def function(a,b,c=100): # 默认参数必须在末尾 |
不定长参数def functionname([formal_args,] *var_args_tuple ):
*argTuple1
2
3
4
5
6
7def function(arg1,*arg2):
print(arg1)
print(arg2)
function(100,"hello","world")
#100
#('hello', 'world')*argDictionary1
2
3
4
5
6
7
8def 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]]:expressionlambda [arg1 [,arg2,.....argn]]:expression[,[arg1[,arg2,...argn]]]
* 与/
1 | def function(a,b,/,c,d,*,e,f): |
a,b不得使用关键字参数
e,f必须使用关键字参数
Tips: 关键字参数后不得使用位置参数
类
- 构造函数
__init__() - next函数
__next__() - raise StopIteration