1. Hello, World!
print("Hello, World!")
2. 变量和基本数据类型:
# 定义变量
name = "Alice"
age = 25
height = 1.75
# 打印变量值
print(f"Name: {name}, Age: {age}, Height: {height}")
3. 判断和循环:
# 判断
x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
# 循环
for i in range(5):
print(i)
# while 循环
count = 0
while count < 3:
print("Count:", count)
count += 1
4. 函数:
# 定义函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
message = greet("Bob")
print(message)
5. 列表和循环:
# 列表
numbers = [1, 2, 3, 4, 5]
# 遍历列表
for num in numbers:
print(num)
# 列表推导式
squares = [x**2 for x in numbers]
print(squares)
6. 字典:
# 字典
person = {'name': 'John', 'age': 30, 'city': 'New York'}
# 访问字典元素
print(person['name'])
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
7. 异常处理:
# 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
except Exception as e:
print(f"An error occurred: {e}")
8. 文件操作:
# 文件操作
with open("example.txt", "w") as file:
file.write("Hello, File!")
with open("example.txt", "r") as file:
content = file.read()
print(content)
9. 面向对象编程:
# 面向对象
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
my_dog = Dog(name="Buddy", age=3)
my_dog.bark()
这些是一些简单的 Python 实例,覆盖了基本的语法、数据类型、流程控制、函数、异常处理等方面。通过运行这些示例,你可以深入理解 Python 编程语言。
转载请注明出处:http://www.zyzy.cn/article/detail/13280/Python3