函数深度解析
函数参数类型
python
复制
下载
# 位置参数 def describe_pet(animal_type, pet_name): print(f"I have a {animal_type} named {pet_name}.") # 关键字参数 describe_pet(animal_type="hamster", pet_name="Harry") # 默认参数 def describe_pet(pet_name, animal_type="dog"): print(f"I have a {animal_type} named {pet_name}.") # 可变参数 def make_pizza(*toppings): print("Making pizza with:") for topping in toppings: print(f"- {topping}")
返回值与作用域
python
复制
下载
def get_formatted_name(first_name, last_name): full_name = f"{first_name} {last_name}" return full_name.title() musician = get_formatted_name('jimi', 'hendrix') print(musician) # 输出: Jimi Hendrix
文件操作
读取文件
python
复制
下载
# 读取整个文件 with open('pi_digits.txt') as file_object: contents = file_object.read() print(contents) # 逐行读取 filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line.rstrip())
写入文件
python
复制
下载
# 写入空文件 filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.") # 追加内容 with open(filename, 'a') as file_object: file_object.write("\nI love creating new games.")
异常处理
python
复制
下载
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!") else: print("Division successful!") finally: print("Execution completed.") # 处理文件不存在异常 try: with open('nonexistent.txt') as f: contents = f.read() except FileNotFoundError: print("Sorry, the file does not exist.")
实战项目:天气查询程序
python
复制
下载
import requests def get_weather(city): api_key = "YOUR_API_KEY" # 实际使用时替换为真实API密钥 base_url = "http://api.openweathermap.org/data/2.5/weather" try: params = {'q': city, 'appid': api_key, 'units': 'metric'} response = requests.get(base_url, params=params) weather_data = response.json() if weather_data['cod'] != 200: print(f"Error: {weather_data['message']}") return print(f"\nWeather in {city}:") print(f"Temperature: {weather_data['main']['temp']}°C") print(f"Humidity: {weather_data['main']['humidity']}%") print(f"Weather: {weather_data['weather'][0]['description']}") except requests.exceptions.RequestException as e: print(f"Error fetching weather data: {e}") while True: city = input("\nEnter a city name (or 'quit' to exit): ") if city.lower() == 'quit': break get_weather(city)
常用标准库介绍
库名称 | 用途 | 示例 |
---|---|---|
os | 操作系统交互 | os.listdir() |
sys | 系统相关功能 | sys.argv |
datetime | 日期时间处理 | datetime.now() |
math | 数学运算 | math.sqrt(16) |
random | 生成随机数 | random.randint(1, 10) |
json | JSON数据处理 | json.loads() |
python
复制
下载
# datetime示例 from datetime import datetime now = datetime.now() print(f"Current date and time: {now}") print(f"Formatted date: {now.strftime('%Y-%m-%d')}")
Python学习资源推荐
-
官方文档: docs.python.org
-
在线教程:
-
互动学习平台:
-
书籍推荐:
-
《Python Crash Course》
-
《Automate the Boring Stuff with Python》
-
下一步学习方向
-
Web开发: 学习Django或Flask框架
-
数据分析: 掌握Pandas、NumPy和Matplotlib
-
自动化脚本: 尝试用Python简化日常工作
-
机器学习: 从Scikit-learn开始AI之旅
-
参与开源: 在GitHub上贡献Python项目
记住,编程最好的学习方式就是实践!尝试用Python解决你生活中的实际问题,你会进步得更快。祝你Python学习之旅愉快!