Python——start

Getting started with Python

  • 赋值变量
    字符串
    saying = "Hello World!"
    saying = 'Hello World!'
  • 列表
    可变(可修改)
    bicycles = ['trek','redline','specialized']
    bicycles.append('ducati')  # 添加元素
  • 元组
    不可变(不可修改)
    dimensions = (1920, 1080)
    print(dimensions[0])       # 正确访问
    # dimensions[0] = 1600     # 会引发TypeError
  • if语句
    条件逻辑
    temperature = 25
    if temperature > 30:
    print("太热了")
    elif 20 <= temperature <= 30:
    print("宜人")
    else:
    print("凉爽")
  • Python字典
    键值对集合
    user = {'name': 'John', 'age': 32}
    user['email'] = 'john@example.com'  # 添加新键
    print(user.get('country', '未知'))  # 安全获取值
  • 输入&while
    交互式程序
    active = True
    while active:
    message = input("输入'quit'退出: ")
    if message == 'quit':
        active = False
    else:
        print(message)
  • 函数
    代码复用
    def make_pizza(size, *toppings):
    """制作披萨的说明"""
    print(f"\n制作{size}寸披萨,配料:")
    for topping in toppings:
        print(f"- {topping}")
    make_pizza(12, 'mushroom', 'cheese')
  • 面向对象编程
    class Car:
    """汽车类示例"""
    def __init__(self, make, model):
        self.make = make
        self.model = model
        self.odometer = 0
    def update_odometer(self, mileage):
        if mileage >= self.odometer:
            self.odometer = mileage
    my_car = Car('Tesla', 'Model S')
    my_car.update_odometer(500)
  • 文件
    数据持久化
    with open('diary.txt', 'w') as file:
    file.write("2025-1-25\n今天学会了Python!")
    with open('diary.txt') as file:
    content = file.readlines()
    print("日记内容:", content)
  • 编写测试
    保证代码质量
    import unittest
    class TestCar(unittest.TestCase):
    def test_odometer(self):
        test_car = Car('Audi', 'A4')
        test_car.update_odometer(1000)
        self.assertEqual(test_car.odometer, 1000)
    if __name__ == '__main__':
    unittest.main()

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部