变量是存储数据的容器。在Python中,你无需声明变量类型,可以直接赋值。
a = 10 # 整数类型
b = 3.14 # 浮点数类型
c = "Hello" # 字符串类型
d = True # 布尔类型
e = None # 空值类型
Python有多种内建的数据类型,常见的包括:
int
):整数类型的数据。float
):带小数点的数字。str
):文本数据。bool
):True 或 False。NoneType
):表示空值或无值。print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'str'>
print(type(d)) # <class 'bool'>
print(type(e)) # <class 'NoneType'>
用于对数字进行基本的数学运算。
x = 10
y = 3
print(x + y) # 加法,输出 13
print(x - y) # 减法,输出 7
print(x * y) # 乘法,输出 30
print(x / y) # 除法,输出 3.3333333333333335
print(x // y) # 地板除法,输出 3
print(x % y) # 取模(余数),输出 1
print(x ** y) # 幂运算,输出 1000
用于比较两个值,返回布尔值(True 或 False)。
print(x == y) # 是否等于,输出 False
print(x != y) # 是否不等于,输出 True
print(x > y) # 是否大于,输出 True
print(x < y) # 是否小于,输出 False
print(x >= y) # 是否大于等于,输出 True
print(x <= y) # 是否小于等于,输出 False
用于进行布尔逻辑运算。
print(x > 5 and y < 5) # 逻辑与,输出 True
print(x > 5 or y > 5) # 逻辑或,输出 True
print(not(x > 5)) # 逻辑非,输出 False
根据条件的真伪执行不同的代码块。
if x > y:
print("x is greater than y")
elif x == y:
print("x is equal to y")
else:
print("x is less than y")
while 循环:在条件为真时反复执行代码块。
count = 0
while count < 5:
print(count)
count += 1
for 循环:遍历一个序列(如列表、元组、字符串等)。
for i in range(5):
print(i)
break 和 continue:控制循环的执行。
for i in range(10):
if i == 5:
break # 退出循环
if i % 2 == 0:
continue # 跳过当前迭代
print(i)
有序可变序列,使用方括号定义。
my_list = [1, 2, 3, 4, 5]
print(my_list[0]) # 访问列表元素,输出 1
my_list.append(6) # 添加元素
my_list.remove(2) # 移除元素
print(my_list) # 输出 [1, 3, 4, 5, 6]
有序不可变序列,使用圆括号定义。
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # 访问元组元素,输出 1
无序不重复元素集,使用花括号定义。
my_set = {1, 2, 3, 4, 5}
my_set.add(6) # 添加元素
my_set.remove(2) # 移除元素
print(my_set) # 输出 {1, 3, 4, 5, 6}
键值对集合,使用花括号定义,键必须是唯一的。
my_dict = {"a": 1, "b": 2, "c": 3}
print(my_dict["a"]) # 访问字典值,输出 1
my_dict["d"] = 4 # 添加键值对
del my_dict["b"] # 删除键值对
print(my_dict) # 输出 {'a': 1, 'c': 3, 'd': 4}
def my_function(a, b):
return a + b
result = my_function(10, 20)
print(result) # 输出 30
def greet(name="World"):
print("Hello, " + name)
greet() # 输出 Hello, World
greet("Python") # 输出 Hello, Python
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 输出 15
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
# 输出:
# name: Alice
# age: 25
# city: New York
class Person:
# 构造函数
def __init__(self, name, age):
self.name = name
self.age = age
# 实例方法
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 创建对象
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
# 调用方法
person1.greet() # 输出 Hello, my name is Alice and I am 30 years old.
person2.greet() # 输出 Hello, my name is Bob and I am 25 years old.
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "w") as file:
file.write("Hello, World!")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This will always be executed.")