Python入门指南(下):函数、文件操作与实战项目

Python进阶学习

函数深度解析

函数参数类型

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)

天气API响应示例

常用标准库介绍

库名称用途示例
os操作系统交互os.listdir()
sys系统相关功能sys.argv
datetime日期时间处理datetime.now()
math数学运算math.sqrt(16)
random生成随机数random.randint(1, 10)
jsonJSON数据处理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学习资源推荐

  1. 官方文档docs.python.org

  2. 在线教程:

  3. 互动学习平台:

  4. 书籍推荐:

    • 《Python Crash Course》

    • 《Automate the Boring Stuff with Python》

Python学习资源

下一步学习方向

  1. Web开发: 学习Django或Flask框架

  2. 数据分析: 掌握Pandas、NumPy和Matplotlib

  3. 自动化脚本: 尝试用Python简化日常工作

  4. 机器学习: 从Scikit-learn开始AI之旅

  5. 参与开源: 在GitHub上贡献Python项目

Python应用领域

记住,编程最好的学习方式就是实践!尝试用Python解决你生活中的实际问题,你会进步得更快。祝你Python学习之旅愉快!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值