Python 编程第一步:基础语法与代码实例
Python 以其简洁易读的语法成为初学者的理想选择。以下从基础语法到实际应用,通过代码实例展示 Python 的核心功能。
变量与数据类型
Python 支持动态类型,无需显式声明变量类型:
name = "Alice" # 字符串
age = 25 # 整数
height = 1.75 # 浮点数
is_student = True # 布尔值
基本运算与字符串操作
数学运算和字符串格式化示例:
x = 10
y = 3
print(f"除法结果: {x / y:.2f}") # 输出保留两位小数
# 字符串拼接
greeting = "Hello, " + name + "!"
# 使用 f-string(Python 3.6+)
greeting = f"Hello, {name}! You are {age} years old."
条件语句与循环
if-elif-else
结构和循环示例:
# 条件判断
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")
# for 循环
for i in range(5): # 0到4
print(i * 2)
# while 循环
count = 0
while count < 3:
print("Count:", count)
count += 1
列表与字典操作
常用数据结构的使用:
# 列表(可变)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # 添加元素
print(fruits[1:3]) # 切片输出 ['banana', 'cherry']
# 字典(键值对)
person = {
"name": "Bob",
"age": 30,
"city": "New York"
}
print(person.get("age", "N/A")) # 安全获取值
函数定义与使用
创建可复用代码块:
def calculate_area(width, height=10):
"""计算矩形面积(默认高度为10)"""
return width * height
area = calculate_area(5) # 使用默认参数
print(f"Area: {area}") # 输出 50
文件读写
处理文本文件的基本操作:
# 写入文件
with open("example.txt", "w") as file:
file.write("This is line 1\n")
file.write("This is line 2\n")
# 读取文件
with open("example.txt", "r") as file:
content = file.readlines()
for line in content:
print(line.strip()) # 去除换行符
异常处理
使用 try-except
捕获错误:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"Error occurred: {e}")
finally:
print("This always executes")
类与面向对象编程
创建自定义类:
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
return f"{self.name} says woof!"
my_dog = Dog("Buddy", "Golden Retriever")
print(my_dog.bark()) # 输出 "Buddy says woof!"
模块导入
使用标准库和第三方模块:
import math
from datetime import datetime
print(math.sqrt(16)) # 4.0
print(datetime.now().year) # 当前年份
# 安装第三方库:pip install requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
实际应用示例
结合多个概念完成具体任务:
# 计算列表中数字的平方并筛选偶数
numbers = [1, 2, 3, 4, 5]
squared_evens = [x**2 for x in numbers if x % 2 == 0]
print(squared_evens) # 输出 [4, 16]
# 使用字典统计单词频率
text = "apple banana apple orange banana apple"
words = text.split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print(frequency) # {'apple': 3, 'banana': 2, 'orange': 1}
通过以上实例可快速掌握 Python 基础编程逻辑,建议通过实际项目加深理解。