Pyth 打印输出
print("Hello, Python!")
2. 变量赋值
x = 10
name = "John"
3. 数据类型
Python 有多种基本数据类型,包括整数、浮点数、字符串、列表(List)、元组(Tuple)、字典(Dictionary)和集合(Set)。
number = 42 # 整数
float_number = 3.14 # 浮点数
greeting = "Hello" # 字符串
names = ["John", "Jane", "Foo"] # 列表
person = ("John", 30) # 元组
ages = {"John": 30, "Jane": 25} # 字典
unique_numbers = {1, 2, 3, 3, 4} # 集合
4. 条件语句
age = 20
if age > 18:
print("You are an adult.")
elif age == 18:
print("You are an adult.")
else:
print("You are a minor.")
5. 循环
Python 中的循环包括 for
循环和 while
循环。
# for 循环
for i in range(5):
print(i)
# while 循环
i = 0
while i < 5:
print(i)
i += 1
6. 列表推导式
squares = [x*x for x in range(10)]
7. 函数定义
def greet(name):
print(f"Hello, {name}!")
greet("John")
8. 类和对象
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.")
person = Person("John", 30)
person.greet()
9. 模块和包
# 导入模块
import math
# 从模块中导入特定函数
from datetime import datetime
10. 文件操作
# 读取文件
with open('file.txt', 'r') as file:
content = file.read()
print(content)
# 写入文件
with open('new_file.txt', 'w') as file:
file.write("Hello, World!")
11. 异常处理
try:
# 尝试执行的代码
result = 10 / 0
except ZeroDivisionError:
# 如果发生了 ZeroDivisionError,则执行这里的代码
print("Cannot divide by zero.")
12. 装饰器
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
Python 的语法简洁而强大,非常适合快速开发和原型制作。