下面介绍一下关于python的基础语法学习
注释
# 单行注释
print("Hello, World!")
# 多行注释。
"""这是一段多行注释"""
print("Hello, World!")
变量和数据类型
# 变量赋值
name = "Alice"
age = 30
print(name, age) # 输出 Alice 30
# 数据类型
number = 10
floating_point = 3.14
boolean = True
string = "Hello, World!"
print(number, floating_point, boolean, string) # 输出 10 3.14 True Hello, World!
字符串操作
# 字符串拼接
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(int(full_name) ) # 输出 John Doe
# 字符串格式化
age = 30
print(f"My name is {first_name} {last_name} and I am {age} years old.") # 输出 My name is John Doe and I am 30 years old.
列表
# 创建列表
numbers = [1, 2, 3, 4, 5]
print(numbers) # 输出 [1, 2, 3, 4, 5]
# 列表操作
numbers.append(6)
print(numbers) # 输出 [1, 2, 3, 4, 5, 6]
元组
# 创建元组
point = (1, 2, 3)
print(point) # 输出 (1, 2, 3)
字典
# 创建字典
person = {"name": "Alice", "age": 30}
print(person) # 输出 {'name': 'Alice', 'age': 30}
if条件语句
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are not an adult yet.") # 输出 You are an adult.
for 循环
# for 循环
for i in range(5):
print(i) # 输出 0 1 2 3 4
while 循环
count = 0
while count < 5:
print(count)
count += 1 # 输出 0 1 2 3 4
函数定义
# 定义函数
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # 输出 Hello, Alice!
模块导入
# 导入模块
import math
print(math.sqrt(16)) # 输出 4.0
异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.") # 输出 Cannot divide by zero.
文件操作
with open("example.txt", "w") as file:
file.write("Hello, World!")
with open("example.txt", "r") as file:
content = file.read()
print(content) # 输出 Hello, World!
类和对象
# 类定义
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name} and I am {self.age} years old.")
alice = Person("Alice", 30)
alice.introduce() # 输出 My name is Alice and I am 30 years old.
列表推导式
# 快速创建列表
squares = [x ** 2 for x in range(5)]
print(squares) # 输出 [0, 1, 4, 9, 16]
# 字典推导式快速创建字典
square_dict = {x: x ** 2 for x in range(5)}
print(square_dict) # 输出 {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
集合
# 创建集合
unique_chars = {char for char in "hello"}
print(unique_chars) # 输出 {'h', 'e', 'l', 'o'}
排序
# 对列表排序
numbers = [3, 1, 4, 1, 5, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出 [1, 1, 3, 4, 5, 9]
过滤
# 使用filter()过滤列表
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 输出 [2, 4]
映射
numbers = [1, 2, 3]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # 输出 [1, 4, 9]
枚举
# enumerate()循环带索引
for i, val in enumerate(['a', 'b', 'c']): print(i, val) # 输出 0 a 1 b 2 c