学习目标

通过本章学习,你将掌握: - Python的基本语法规则 - 变量的定义和使用 - Python的数据类型 - 运算符和表达式 - 输入输出操作 - 字符串处理技巧 - 注释和文档编写

3.1 Python语法基础

缩进规则

Python使用缩进来表示代码块,这是Python的重要特性:

# 正确的缩进
if True:
    print("这是正确的缩进")  # 4个空格
    if True:
        print("嵌套缩进")      # 8个空格

# 错误的缩进会导致IndentationError
# if True:
# print("错误:没有缩进")

# 混合使用空格和Tab会导致问题
# 建议:只使用空格,设置编辑器显示空白字符

语句和表达式

# 语句:执行某个操作
print("Hello, World!")  # 函数调用语句
x = 10                   # 赋值语句

# 表达式:计算并返回值
result = 2 + 3 * 4      # 算术表达式
is_valid = x > 5        # 比较表达式

# 复合语句
if x > 5:
    print("x大于5")
else:
    print("x不大于5")

行连接

# 使用反斜杠连接行
total = 1 + 2 + 3 + \
        4 + 5 + 6

# 在括号内可以自然换行
total = (1 + 2 + 3 +
         4 + 5 + 6)

# 字符串连接
message = "这是一个很长的字符串," \
          "需要分行显示"

# 列表、字典等可以跨行
fruits = [
    "apple",
    "banana",
    "orange"
]

3.2 变量和标识符

变量定义

# Python是动态类型语言,变量不需要声明类型
name = "Alice"          # 字符串
age = 25               # 整数
height = 1.68          # 浮点数
is_student = True      # 布尔值

# 变量可以重新赋值为不同类型
x = 10
print(type(x))         # <class 'int'>
x = "Hello"
print(type(x))         # <class 'str'>

# 多重赋值
a, b, c = 1, 2, 3
x = y = z = 0

# 交换变量值
a, b = b, a
print(f"a={a}, b={b}")  # a=2, b=1

标识符命名规则

# 合法的标识符
name = "Alice"
age_in_years = 25
_private_var = "私有变量"
CLASS_CONSTANT = "常量"
my_function = lambda x: x * 2

# 不合法的标识符(会导致语法错误)
# 2name = "错误:以数字开头"
# my-var = "错误:包含连字符"
# class = "错误:使用关键字"

# Python关键字(不能用作标识符)
import keyword
print(keyword.kwlist)
# ['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert', 
#  'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 
#  'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 
#  'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 
#  'return', 'try', 'while', 'with', 'yield']

命名约定

# 变量和函数:小写字母,下划线分隔
user_name = "alice"
max_count = 100

def calculate_total(items):
    return sum(items)

# 常量:全大写字母,下划线分隔
PI = 3.14159
MAX_SIZE = 1000
DEFAULT_COLOR = "blue"

# 类名:首字母大写的驼峰命名
class UserAccount:
    pass

class DatabaseConnection:
    pass

# 私有变量:以下划线开头
class MyClass:
    def __init__(self):
        self._protected_var = "受保护的变量"
        self.__private_var = "私有变量"

# 特殊方法:双下划线包围
class MyClass:
    def __init__(self):
        pass
    
    def __str__(self):
        return "MyClass instance"

3.3 数据类型

数字类型

# 整数 (int)
positive_int = 42
negative_int = -17
big_int = 123456789012345678901234567890  # Python支持任意精度整数

# 不同进制表示
binary = 0b1010      # 二进制,值为10
octal = 0o12         # 八进制,值为10
hexadecimal = 0xa    # 十六进制,值为10

print(f"二进制{binary}, 八进制{octal}, 十六进制{hexadecimal}")

# 浮点数 (float)
pi = 3.14159
scientific = 1.23e-4  # 科学计数法,值为0.000123
infinity = float('inf')
not_a_number = float('nan')

# 复数 (complex)
complex_num = 3 + 4j
complex_num2 = complex(3, 4)
print(f"实部: {complex_num.real}, 虚部: {complex_num.imag}")

# 数字类型转换
int_val = int(3.14)      # 3
float_val = float(42)    # 42.0
complex_val = complex(5) # (5+0j)

# 数学运算
import math
print(f"平方根: {math.sqrt(16)}")
print(f"向上取整: {math.ceil(3.2)}")
print(f"向下取整: {math.floor(3.8)}")
print(f"绝对值: {abs(-5)}")
print(f"幂运算: {pow(2, 3)}")

字符串类型

# 字符串定义
single_quote = 'Hello'
double_quote = "World"
triple_quote = '''多行
字符串
内容'''

# 原始字符串(不转义)
raw_string = r"C:\Users\name\Documents"
regex_pattern = r"\d+\w+"

# 字符串格式化
name = "Alice"
age = 25

# 旧式格式化
old_format = "姓名: %s, 年龄: %d" % (name, age)

# str.format()方法
new_format = "姓名: {}, 年龄: {}".format(name, age)
named_format = "姓名: {name}, 年龄: {age}".format(name=name, age=age)

# f-string(推荐,Python 3.6+)
f_string = f"姓名: {name}, 年龄: {age}"
f_expression = f"明年年龄: {age + 1}"
f_format = f"身高: {1.68:.2f}米"  # 保留两位小数

print(f_string)
print(f_expression)
print(f_format)

# 字符串操作
text = "Hello, Python!"
print(f"长度: {len(text)}")
print(f"大写: {text.upper()}")
print(f"小写: {text.lower()}")
print(f"首字母大写: {text.capitalize()}")
print(f"标题格式: {text.title()}")
print(f"是否以Hello开头: {text.startswith('Hello')}")
print(f"是否以!结尾: {text.endswith('!')}")
print(f"查找Python位置: {text.find('Python')}")
print(f"替换: {text.replace('Python', 'World')}")

# 字符串分割和连接
sentence = "apple,banana,orange"
fruits = sentence.split(",")
print(f"分割结果: {fruits}")

joined = " | ".join(fruits)
print(f"连接结果: {joined}")

# 字符串去除空白
spaced_text = "  Hello World  "
print(f"去除两端空白: '{spaced_text.strip()}'")
print(f"去除左侧空白: '{spaced_text.lstrip()}'")
print(f"去除右侧空白: '{spaced_text.rstrip()}'")

布尔类型

# 布尔值
is_true = True
is_false = False

# 布尔运算
print(f"True and False: {True and False}")
print(f"True or False: {True or False}")
print(f"not True: {not True}")

# 真值测试
# 以下值被认为是False
falsy_values = [
    False,
    None,
    0,
    0.0,
    0j,
    "",
    [],
    {},
    set()
]

for value in falsy_values:
    print(f"{repr(value)} is {bool(value)}")

# 其他值都被认为是True
truthy_values = [True, 1, "hello", [1, 2], {"key": "value"}]
for value in truthy_values:
    print(f"{repr(value)} is {bool(value)}")

# 比较运算返回布尔值
print(f"5 > 3: {5 > 3}")
print(f"'abc' == 'abc': {'abc' == 'abc'}")
print(f"10 in [1, 2, 10]: {10 in [1, 2, 10]}")

None类型

# None表示空值或无值
result = None
print(f"result的值: {result}")
print(f"result的类型: {type(result)}")

# None的使用场景
def find_user(user_id):
    # 模拟查找用户
    if user_id == 1:
        return {"name": "Alice", "age": 25}
    else:
        return None  # 未找到用户

user = find_user(2)
if user is None:
    print("用户不存在")
else:
    print(f"找到用户: {user}")

# 注意:使用 is 而不是 == 来检查None
value = None
print(f"value is None: {value is None}")      # 推荐
print(f"value == None: {value == None}")      # 不推荐

3.4 运算符

算术运算符

a, b = 10, 3

print(f"加法: {a} + {b} = {a + b}")
print(f"减法: {a} - {b} = {a - b}")
print(f"乘法: {a} * {b} = {a * b}")
print(f"除法: {a} / {b} = {a / b}")
print(f"整除: {a} // {b} = {a // b}")
print(f"取余: {a} % {b} = {a % b}")
print(f"幂运算: {a} ** {b} = {a ** b}")

# 字符串和列表的运算
print(f"字符串重复: {'Hi' * 3}")
print(f"列表重复: {[1, 2] * 3}")
print(f"字符串连接: {'Hello' + ' World'}")
print(f"列表连接: {[1, 2] + [3, 4]}")

比较运算符

x, y = 5, 10

print(f"{x} == {y}: {x == y}")
print(f"{x} != {y}: {x != y}")
print(f"{x} < {y}: {x < y}")
print(f"{x} <= {y}: {x <= y}")
print(f"{x} > {y}: {x > y}")
print(f"{x} >= {y}: {x >= y}")

# 链式比较
age = 25
print(f"18 <= {age} <= 65: {18 <= age <= 65}")

# 字符串比较(按字典序)
print(f"'apple' < 'banana': {'apple' < 'banana'}")
print(f"'Apple' < 'apple': {'Apple' < 'apple'}")

# 身份比较
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(f"a == b: {a == b}")  # True,内容相同
print(f"a is b: {a is b}")  # False,不是同一个对象
print(f"a is c: {a is c}")  # True,是同一个对象

# 成员测试
fruits = ['apple', 'banana', 'orange']
print(f"'apple' in fruits: {'apple' in fruits}")
print(f"'grape' not in fruits: {'grape' not in fruits}")

逻辑运算符

# and, or, not
print(f"True and False: {True and False}")
print(f"True or False: {True or False}")
print(f"not True: {not True}")

# 短路求值
def expensive_operation():
    print("执行昂贵的操作")
    return True

# and的短路求值
result = False and expensive_operation()  # expensive_operation不会被调用
print(f"False and expensive_operation(): {result}")

# or的短路求值
result = True or expensive_operation()    # expensive_operation不会被调用
print(f"True or expensive_operation(): {result}")

# 逻辑运算符返回操作数,不一定是布尔值
print(f"'hello' and 'world': {'hello' and 'world'}")
print(f"'' or 'default': {'' or 'default'}")
print(f"None or 0 or 'value': {None or 0 or 'value'}")

赋值运算符

# 基本赋值
x = 10

# 复合赋值运算符
x += 5   # x = x + 5
print(f"x += 5: {x}")

x -= 3   # x = x - 3
print(f"x -= 3: {x}")

x *= 2   # x = x * 2
print(f"x *= 2: {x}")

x /= 4   # x = x / 4
print(f"x /= 4: {x}")

x //= 2  # x = x // 2
print(f"x //= 2: {x}")

x %= 3   # x = x % 3
print(f"x %= 3: {x}")

x **= 3  # x = x ** 3
print(f"x **= 3: {x}")

# 海象运算符(Python 3.8+)
# 在表达式中赋值
if (n := len([1, 2, 3, 4, 5])) > 3:
    print(f"列表长度 {n} 大于3")

# 在循环中使用
data = [1, 2, 3, 4, 5]
while (item := data.pop() if data else None) is not None:
    print(f"处理项目: {item}")

位运算符

a, b = 12, 10  # 二进制: 1100, 1010

print(f"a = {a:04b}, b = {b:04b}")
print(f"a & b = {a & b:04b} ({a & b})")   # 按位与
print(f"a | b = {a | b:04b} ({a | b})")   # 按位或
print(f"a ^ b = {a ^ b:04b} ({a ^ b})")   # 按位异或
print(f"~a = {~a & 0xF:04b} ({~a & 0xF})") # 按位取反
print(f"a << 2 = {a << 2:06b} ({a << 2})") # 左移
print(f"a >> 2 = {a >> 2:02b} ({a >> 2})") # 右移

# 位运算的应用
# 检查奇偶性
def is_even(n):
    return (n & 1) == 0

print(f"12是偶数: {is_even(12)}")
print(f"13是偶数: {is_even(13)}")

# 交换两个数(不使用临时变量)
x, y = 5, 10
print(f"交换前: x={x}, y={y}")
x ^= y
y ^= x
x ^= y
print(f"交换后: x={x}, y={y}")

3.5 输入输出

输出函数print()

# 基本输出
print("Hello, World!")
print("Python", "is", "awesome")

# 指定分隔符
print("apple", "banana", "orange", sep=", ")
print("2024", "12", "25", sep="-")

# 指定结束符
print("Loading", end="")
for i in range(3):
    print(".", end="")
print(" Done!")

# 输出到文件
with open("output.txt", "w", encoding="utf-8") as f:
    print("这行文字将写入文件", file=f)
    print("第二行文字", file=f)

# 格式化输出
name = "Alice"
age = 25
score = 95.5

print(f"学生: {name}")
print(f"年龄: {age}岁")
print(f"成绩: {score:.1f}分")

# 对齐和填充
print(f"{'左对齐':<10}|")
print(f"{'右对齐':>10}|")
print(f"{'居中':^10}|")
print(f"{'填充':*^10}|")

# 数字格式化
number = 1234567.89
print(f"千分位分隔: {number:,}")
print(f"科学计数法: {number:.2e}")
print(f"百分比: {0.85:.1%}")

# 进制转换输出
num = 255
print(f"十进制: {num}")
print(f"二进制: {num:b}")
print(f"八进制: {num:o}")
print(f"十六进制: {num:x}")
print(f"十六进制(大写): {num:X}")

输入函数input()

# 基本输入
name = input("请输入你的姓名: ")
print(f"你好, {name}!")

# 输入数字(需要类型转换)
try:
    age = int(input("请输入你的年龄: "))
    print(f"你今年{age}岁")
except ValueError:
    print("请输入有效的数字")

# 输入浮点数
try:
    height = float(input("请输入你的身高(米): "))
    print(f"你的身高是{height:.2f}米")
except ValueError:
    print("请输入有效的数字")

# 输入多个值
data = input("请输入三个数字,用空格分隔: ")
numbers = [int(x) for x in data.split()]
print(f"你输入的数字是: {numbers}")
print(f"它们的和是: {sum(numbers)}")

# 安全的输入处理
def get_integer_input(prompt, min_val=None, max_val=None):
    while True:
        try:
            value = int(input(prompt))
            if min_val is not None and value < min_val:
                print(f"值必须大于等于{min_val}")
                continue
            if max_val is not None and value > max_val:
                print(f"值必须小于等于{max_val}")
                continue
            return value
        except ValueError:
            print("请输入有效的整数")

# 使用安全输入函数
age = get_integer_input("请输入年龄(0-150): ", 0, 150)
print(f"你的年龄是{age}岁")

# 确认输入
def get_yes_no_input(prompt):
    while True:
        response = input(prompt + " (y/n): ").lower().strip()
        if response in ['y', 'yes', '是', '对']:
            return True
        elif response in ['n', 'no', '否', '不']:
            return False
        else:
            print("请输入 y/yes 或 n/no")

confirm = get_yes_no_input("确认要继续吗?")
if confirm:
    print("继续执行...")
else:
    print("操作已取消")

文件输入输出

# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("第一行文本\n")
    file.write("第二行文本\n")
    
    # 写入多行
    lines = ["第三行\n", "第四行\n", "第五行\n"]
    file.writelines(lines)

# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:
    # 读取全部内容
    content = file.read()
    print("文件全部内容:")
    print(content)

# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:
    print("逐行读取:")
    for line_number, line in enumerate(file, 1):
        print(f"第{line_number}行: {line.strip()}")

# 读取为列表
with open("example.txt", "r", encoding="utf-8") as file:
    lines = file.readlines()
    print(f"文件共有{len(lines)}行")

# 追加写入
with open("example.txt", "a", encoding="utf-8") as file:
    file.write("追加的新行\n")

# 处理CSV文件
import csv

# 写入CSV
data = [
    ["姓名", "年龄", "城市"],
    ["Alice", 25, "北京"],
    ["Bob", 30, "上海"],
    ["Charlie", 35, "广州"]
]

with open("people.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.writer(file)
    writer.writerows(data)

# 读取CSV
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 使用字典读取CSV
with open("people.csv", "r", encoding="utf-8") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(f"姓名: {row['姓名']}, 年龄: {row['年龄']}, 城市: {row['城市']}")

3.6 注释和文档

单行注释

# 这是单行注释
print("Hello")  # 行末注释

# 多行单行注释
# 这是第一行注释
# 这是第二行注释
# 这是第三行注释

# 注释的最佳实践
# 1. 解释为什么,而不是做什么
# 2. 保持注释简洁明了
# 3. 及时更新注释

# 好的注释示例
user_count = get_active_users()  # 获取活跃用户数用于统计报告

# 不好的注释示例
# user_count = get_active_users()  # 调用get_active_users函数

多行注释和文档字符串

"""
这是多行注释,通常用作模块文档
描述模块的功能、作者、版本等信息

作者: Python学习者
版本: 1.0
日期: 2024-01-01
"""

def calculate_area(length, width):
    """
    计算矩形面积
    
    Args:
        length (float): 矩形的长度
        width (float): 矩形的宽度
    
    Returns:
        float: 矩形的面积
    
    Raises:
        ValueError: 当长度或宽度为负数时
    
    Examples:
        >>> calculate_area(5, 3)
        15.0
        >>> calculate_area(2.5, 4)
        10.0
    """
    if length < 0 or width < 0:
        raise ValueError("长度和宽度必须为非负数")
    
    return length * width

class Rectangle:
    """
    矩形类
    
    这个类用于表示矩形,并提供计算面积和周长的方法。
    
    Attributes:
        length (float): 矩形的长度
        width (float): 矩形的宽度
    """
    
    def __init__(self, length, width):
        """
        初始化矩形
        
        Args:
            length (float): 矩形的长度
            width (float): 矩形的宽度
        """
        self.length = length
        self.width = width
    
    def area(self):
        """
        计算矩形面积
        
        Returns:
            float: 矩形的面积
        """
        return self.length * self.width
    
    def perimeter(self):
        """
        计算矩形周长
        
        Returns:
            float: 矩形的周长
        """
        return 2 * (self.length + self.width)

# 访问文档字符串
print(calculate_area.__doc__)
print(Rectangle.__doc__)
print(Rectangle.area.__doc__)

# 使用help()函数查看文档
help(calculate_area)
help(Rectangle)

类型注解(Type Hints)

from typing import List, Dict, Optional, Union, Tuple

# 基本类型注解
def greet(name: str) -> str:
    """问候函数"""
    return f"Hello, {name}!"

def add_numbers(a: int, b: int) -> int:
    """加法函数"""
    return a + b

def calculate_average(numbers: List[float]) -> float:
    """计算平均值"""
    return sum(numbers) / len(numbers)

# 复杂类型注解
def process_user_data(user_data: Dict[str, Union[str, int]]) -> Optional[str]:
    """
    处理用户数据
    
    Args:
        user_data: 包含用户信息的字典
    
    Returns:
        处理结果,如果失败返回None
    """
    if "name" in user_data and "age" in user_data:
        return f"用户: {user_data['name']}, 年龄: {user_data['age']}"
    return None

# 类的类型注解
class Student:
    def __init__(self, name: str, age: int, grades: List[float]) -> None:
        self.name: str = name
        self.age: int = age
        self.grades: List[float] = grades
    
    def get_average_grade(self) -> float:
        return sum(self.grades) / len(self.grades)
    
    def add_grade(self, grade: float) -> None:
        self.grades.append(grade)

# 变量类型注解
student_count: int = 0
student_names: List[str] = []
grade_mapping: Dict[str, float] = {"A": 90.0, "B": 80.0, "C": 70.0}

# 函数类型注解
from typing import Callable

def apply_operation(x: int, y: int, operation: Callable[[int, int], int]) -> int:
    """应用操作函数"""
    return operation(x, y)

def multiply(a: int, b: int) -> int:
    return a * b

result = apply_operation(5, 3, multiply)
print(f"结果: {result}")

3.7 综合示例:简单计算器

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单计算器程序

这个程序实现了一个简单的命令行计算器,支持基本的四则运算。

作者: Python学习者
版本: 1.0
日期: 2024-01-01
"""

import sys
from typing import Union, Optional

class Calculator:
    """
    简单计算器类
    
    支持加法、减法、乘法、除法运算
    """
    
    def __init__(self) -> None:
        """初始化计算器"""
        self.history: list = []  # 存储计算历史
    
    def add(self, a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
        """加法运算"""
        result = a + b
        self._add_to_history(f"{a} + {b} = {result}")
        return result
    
    def subtract(self, a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
        """减法运算"""
        result = a - b
        self._add_to_history(f"{a} - {b} = {result}")
        return result
    
    def multiply(self, a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
        """乘法运算"""
        result = a * b
        self._add_to_history(f"{a} * {b} = {result}")
        return result
    
    def divide(self, a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
        """
        除法运算
        
        Args:
            a: 被除数
            b: 除数
        
        Returns:
            除法结果
        
        Raises:
            ZeroDivisionError: 当除数为0时
        """
        if b == 0:
            raise ZeroDivisionError("除数不能为0")
        
        result = a / b
        self._add_to_history(f"{a} / {b} = {result}")
        return result
    
    def _add_to_history(self, operation: str) -> None:
        """添加操作到历史记录"""
        self.history.append(operation)
    
    def get_history(self) -> list:
        """获取计算历史"""
        return self.history.copy()
    
    def clear_history(self) -> None:
        """清空计算历史"""
        self.history.clear()

def get_number_input(prompt: str) -> float:
    """
    获取数字输入
    
    Args:
        prompt: 输入提示
    
    Returns:
        用户输入的数字
    """
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("请输入有效的数字!")

def get_operation_input() -> str:
    """
    获取运算符输入
    
    Returns:
        用户选择的运算符
    """
    operations = {
        '1': '+',
        '2': '-',
        '3': '*',
        '4': '/'
    }
    
    while True:
        print("\n请选择运算:")
        print("1. 加法 (+)")
        print("2. 减法 (-)")
        print("3. 乘法 (*)")
        print("4. 除法 (/)")
        
        choice = input("请输入选择 (1-4): ").strip()
        
        if choice in operations:
            return operations[choice]
        else:
            print("无效的选择,请重新输入!")

def main() -> None:
    """
    主函数
    """
    print("=" * 40)
    print("       欢迎使用简单计算器")
    print("=" * 40)
    
    calculator = Calculator()
    
    while True:
        try:
            # 获取用户输入
            num1 = get_number_input("请输入第一个数字: ")
            operation = get_operation_input()
            num2 = get_number_input("请输入第二个数字: ")
            
            # 执行计算
            if operation == '+':
                result = calculator.add(num1, num2)
            elif operation == '-':
                result = calculator.subtract(num1, num2)
            elif operation == '*':
                result = calculator.multiply(num1, num2)
            elif operation == '/':
                result = calculator.divide(num1, num2)
            
            # 显示结果
            print(f"\n结果: {num1} {operation} {num2} = {result}")
            
            # 询问是否继续
            while True:
                continue_calc = input("\n是否继续计算? (y/n): ").lower().strip()
                if continue_calc in ['y', 'yes', '是']:
                    break
                elif continue_calc in ['n', 'no', '否']:
                    # 显示历史记录
                    history = calculator.get_history()
                    if history:
                        print("\n计算历史:")
                        print("-" * 30)
                        for i, record in enumerate(history, 1):
                            print(f"{i}. {record}")
                    
                    print("\n感谢使用计算器!再见!")
                    sys.exit(0)
                else:
                    print("请输入 y/yes 或 n/no")
        
        except ZeroDivisionError as e:
            print(f"\n错误: {e}")
        except KeyboardInterrupt:
            print("\n\n程序被用户中断")
            sys.exit(0)
        except Exception as e:
            print(f"\n发生未知错误: {e}")

if __name__ == "__main__":
    main()

运行计算器:

python calculator.py

本章小结

本章我们学习了Python的基本语法:

  1. 语法基础:缩进规则、语句和表达式、行连接
  2. 变量标识符:命名规则、命名约定、关键字
  3. 数据类型:数字、字符串、布尔值、None类型
  4. 运算符:算术、比较、逻辑、赋值、位运算符
  5. 输入输出:print()函数、input()函数、文件操作
  6. 注释文档:单行注释、文档字符串、类型注解
  7. 综合应用:通过计算器项目整合所学知识

下一章预告

下一章我们将学习《控制结构》,内容包括: - 条件语句(if/elif/else) - 循环语句(for/while) - 循环控制(break/continue) - 异常处理(try/except) - 上下文管理器(with语句)

练习题

基础练习

  1. 变量操作

    • 定义不同类型的变量
    • 进行类型转换
    • 使用f-string格式化输出
  2. 运算符练习

    • 编写程序计算圆的面积和周长
    • 实现温度转换(摄氏度与华氏度)
    • 使用位运算实现简单的加密解密

进阶练习

  1. 字符串处理

    • 编写程序统计字符串中各字符的出现次数
    • 实现简单的密码强度检查
    • 编写文本格式化工具
  2. 输入输出

    • 编写程序读取CSV文件并进行数据分析
    • 实现简单的日志记录功能
    • 创建配置文件读写工具

综合练习

  1. 个人信息管理系统
    • 使用字典存储个人信息
    • 实现信息的增删改查
    • 支持数据的文件保存和加载

提示:多练习代码,熟练掌握基本语法是后续学习的基础。