python learn
大约 1 分钟
python learn
基本语法
- python不使用大括号来定义代码块,而是使用缩进来定义代码块。
- python中使用#来注释代码
- python中使用三引号('''或""")来定义多行字符串
- python中使用冒号(:)来定义函数、类、循环、条件语句等代码块
- python是动态类型语言,无需提前声明变量,类型在运行时确定
基本类型
- int 整数
- float 浮点数
- bool 布尔值
- str 字符串
容器类型
- list 列表,类似c#的list
- tuple 元组,只读列表
- dict 字典,类似c#的dictionary
- set 集合,类似c#的hashSet
特殊类型
None 空值,类似c#中的null
bytes 二进制数据,如
text = b"hello"
range 范围,如
for i in range(10): print(i)
自定义类型
class 类,如
class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print("Hello, my name is " + self.name + ", I'm " + str(self.age) + " years old.")
function 函数,如
def add(a, b): return a + b
throw & raise
python中抛出异常不用throw,而是使用raise
raise Exception("error message")
try & except
@app.post("/test_4")
async def test_4():
try:
print('我是被try包裹的代码.')
raise HTTPException("我主动抛出异常了.")
except Exception as e:
print(e)
return 'hello'