- Python 是动态类型语言,变量不需要预先声明类型
- 变量名区分大小写
- 命名规则:字母、数字、下划线组成,不能以数字开头
name = "张三"
age = 25
height = 1.75
is_student = True
- 数字(Numbers):整数(int)、浮点数(float)、复数(complex)
- 字符串(String):使用单引号或双引号
- 布尔值(Boolean):True 或 False
- 列表(List):有序、可变
- 元组(Tuple):有序、不可变
- 字典(Dictionary):键值对
- 集合(Set):无序、不重复
x = 10
y = 3.14
z = 1 + 2j
s1 = 'Hello'
s2 = "World"
fruits = ['apple', 'banana', 'orange']
coordinates = (10, 20)
person = {'name': '张三', 'age': 25}
unique_numbers = {1, 2, 3, 4, 5}
+:加法-:减法*:乘法/:除法//:整除%:取余**:幂运算
==:等于!=:不等于>:大于<:小于>=:大于等于<=:小于等于
if condition:
elif another_condition:
else:
for i in range(5):
print(i)
count = 0
while count < 5:
print(count)
count += 1
def function_name(parameters):
"""
函数文档字符串
"""
return result
def greet(name):
return f"Hello, {name}!"
message = greet("张三")
import math
from datetime import datetime
import numpy as np
def my_function():
pass
import mymodule
mymodule.my_function()
try:
result = 10 / 0
except ZeroDivisionError:
print("除数不能为零")
except Exception as e:
print(f"发生错误:{e}")
finally:
print("清理工作")
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
with open('file.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!')
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"你好,我是{self.name},今年{self.age}岁"
person = Person("张三", 25)
print(person.greet())