Python基础语法详解

Python是一种易于学习但功能强大的编程语言,其语法简洁明了。本文将详细介绍Python的基础语法,帮助初学者快速入门。

一、Python的基本概念

1. 解释型语言

Python是一种解释型语言,不需要编译成机器码,而是由解释器逐行执行代码。这使得Python具有良好的跨平台性和快速的开发效率。

2. 缩进和代码块

与其他编程语言不同,Python使用缩进来表示代码块,而不是使用大括号{}。这是Python语法的一个重要特点:

if True:
    print("这是一个代码块")  # 缩进的代码属于if语句
    print("这也是代码块的一部分")
print("这不属于if语句的代码块")

注意:缩进必须一致,通常使用4个空格或1个制表符(Tab)。混合使用空格和制表符可能导致错误。

3. 注释

注释用于解释代码,提高代码的可读性。Python中的注释有两种:

  • 单行注释:使用#开头

    # 这是一个单行注释
    print("Hello, World!")  # 这也是一个注释
    
  • 多行注释:使用三个单引号'''或三个双引号"""包围

    '''
    这是一个多行注释
    可以跨越多行
    '''
    """
    这也是一个多行注释
    使用双引号
    """
    

二、变量和数据类型

1. 变量定义

Python中的变量不需要声明类型,可以直接赋值:

x = 10  # 整数
name = "Python"  # 字符串
is_valid = True  # 布尔值
pi = 3.14159  # 浮点数

变量命名规则

  • 变量名必须以字母或下划线_开头
  • 变量名只能包含字母、数字和下划线
  • 变量名区分大小写(nameName是不同的变量)
  • 不能使用Python关键字(如ifforwhile等)作为变量名

2. 基本数据类型

Python支持多种数据类型,以下是最常用的几种:

(1) 数字类型

  • 整数(int):如10-50
  • 浮点数(float):如3.14-0.52.0
  • 复数(complex):如1+2j3j
# 整数
a = 10
print(type(a))  # <class 'int'>

# 浮点数
b = 3.14
print(type(b))  # <class 'float'>

# 复数
c = 1 + 2j
print(type(c))  # <class 'complex'>

(2) 字符串(str)

字符串是由字符组成的序列,可以使用单引号'、双引号"或三引号'''/"""表示:

# 单引号字符串
str1 = 'Hello'

# 双引号字符串
str2 = "World"

# 三引号字符串(可以包含换行)
str3 = '''Hello
World'''  # 多行字符串

# 转义字符
str4 = "He said, \"Hello!\""

字符串操作:

# 字符串拼接
full_name = "张" + "荣殿"

# 字符串重复
stars = "*" * 5  # "*****"

# 字符串索引(从0开始)
text = "Python"
first_char = text[0]  # "P"
last_char = text[-1]  # "n"(负数索引从末尾开始)

# 字符串切片
substring = text[1:4]  # "yth"(从索引1到3,不包含4)

(3) 布尔值(bool)

布尔值只有两个值:TrueFalse,用于表示真和假:

is_student = True
is_teacher = False

# 布尔运算
result1 = True and False  # False
result2 = True or False   # True
result3 = not True        # False

(4) None类型

None表示空值或不存在的值:

x = None
print(x is None)  # True

3. 容器类型

Python提供了多种容器类型来存储多个值:

(1) 列表(list)

列表是有序、可变的容器,可以存储不同类型的元素:

# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["apple", 10, True, 3.14]

# 访问元素
first_fruit = fruits[0]  # "apple"
last_fruit = fruits[-1]  # "orange"

# 修改元素
fruits[1] = "grape"  # 现在fruits是["apple", "grape", "orange"]

# 添加元素
fruits.append("watermelon")  # 在末尾添加
fruits.insert(1, "pear")  # 在索引1处插入

# 删除元素
fruits.remove("apple")  # 删除指定值的元素
popped = fruits.pop()  # 删除并返回末尾元素
popped_index = fruits.pop(0)  # 删除并返回指定索引的元素

# 列表切片
subset = numbers[1:4]  # [2, 3, 4]

(2) 元组(tuple)

元组是有序、不可变的容器,使用圆括号()表示:

# 创建元组
coordinates = (10, 20)
colors = ("red", "green", "blue")

# 访问元素
y = coordinates[1]  # 20

# 注意:元组不可修改
# coordinates[0] = 5  # 这会引发TypeError

# 元组解包
x, y = coordinates  # x=10, y=20

(3) 集合(set)

集合是无序、不重复的容器,使用花括号{}表示:

# 创建集合
fruits = {"apple", "banana", "orange"}
duplicates = {1, 2, 2, 3, 4, 4, 5}  # 会自动去重,结果是{1, 2, 3, 4, 5}

# 添加元素
fruits.add("grape")

# 删除元素
fruits.remove("apple")  # 如果元素不存在会引发KeyError
fruits.discard("watermelon")  # 如果元素不存在不会引发错误

# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

union = set1 | set2  # 并集 {1, 2, 3, 4, 5, 6}
intersection = set1 & set2  # 交集 {3, 4}
difference = set1 - set2  # 差集 {1, 2}
symmetric_diff = set1 ^ set2  # 对称差集 {1, 2, 5, 6}

(4) 字典(dict)

字典是无序的键值对集合,使用花括号{}表示,键值对之间用冒号:分隔:

# 创建字典
person = {
    "name": "张荣殿",
    "age": 30,
    "is_student": False,
    "hobbies": ["阅读", "编程", "旅行"]
}

# 访问元素
name = person["name"]  # "张荣殿"
age = person.get("age")  # 30

# 添加或修改元素
person["city"] = "北京"  # 添加新键值对
person["age"] = 31  # 修改已有键的值

# 删除元素
person.pop("is_student")  # 删除并返回指定键的值
person.popitem()  # 删除并返回最后一个键值对

del person["hobbies"]  # 删除指定键值对

# 遍历字典
for key in person:  # 遍历键
    print(key, person[key])

for key, value in person.items():  # 遍历键值对
    print(key, value)

三、运算符

Python支持多种运算符,用于执行各种操作:

1. 算术运算符

运算符 描述 示例
+ 加法 a + b
- 减法 a - b
* 乘法 a * b
/ 除法(结果为浮点数) a / b
// 整数除法(向下取整) a // b
% 取余(模运算) a % b
** 幂运算 a ** b(a的b次方)
a = 10
b = 3

print(a + b)  # 13
print(a - b)  # 7
print(a * b)  # 30
print(a / b)  # 3.3333333333333335
print(a // b)  # 3
print(a % b)  # 1
print(a ** b)  # 1000

2. 比较运算符

运算符 描述 示例
== 等于 a == b
!= 不等于 a != b
< 小于 a < b
> 大于 a > b
<= 小于等于 a <= b
>= 大于等于 a >= b
x = 5
y = 10

print(x == y)  # False
print(x != y)  # True
print(x < y)  # True
print(x > y)  # False
print(x <= y)  # True
print(x >= y)  # False

3. 赋值运算符

运算符 描述 示例
= 简单赋值 x = 10
+= 加法赋值 x += 5(等价于x = x + 5)
-= 减法赋值 x -= 5(等价于x = x - 5)
*= 乘法赋值 x *= 5(等价于x = x * 5)
/= 除法赋值 x /= 5(等价于x = x / 5)
//= 整数除法赋值 x //= 5(等价于x = x // 5)
%= 取余赋值 x %= 5(等价于x = x % 5)
**= 幂赋值 x **= 5(等价于x = x ** 5)

4. 逻辑运算符

运算符 描述 示例
and 逻辑与 x and y
or 逻辑或 x or y
not 逻辑非 not x
x = True
y = False

print(x and y)  # False
print(x or y)  # True
print(not x)  # False

5. 成员运算符

运算符 描述 示例
in 如果在序列中找到值返回True 'a' in 'apple'
not in 如果在序列中找不到值返回True 'x' not in 'apple'
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)  # True
print("grape" not in fruits)  # True

person = {"name": "张荣殿", "age": 30}
print("name" in person)  # True(检查键是否存在)
print("张荣殿" in person)  # False(默认检查键)

6. 身份运算符

运算符 描述 示例
is 检查两个变量是否引用同一个对象 x is y
is not 检查两个变量是否引用不同的对象 x is not y
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x == y)  # True(值相同)
print(x is y)  # False(不是同一个对象)
print(x is z)  # True(是同一个对象)

四、控制流程

1. 条件语句(if-elif-else)

条件语句用于根据条件执行不同的代码块:

age = 25

if age < 18:
    print("未成年人")
elif 18 <= age < 60:
    print("成年人")
else:
    print("老年人")

2. 循环语句

(1) for循环

for循环用于遍历序列(如列表、元组、字符串等):

# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(fruit)

# 遍历字符串
for char in "Python":
    print(char)

# 使用range()函数生成序列
for i in range(5):  # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):  # 1, 2, 3, 4, 5
    print(i)

for i in range(1, 10, 2):  # 1, 3, 5, 7, 9(步长为2)
    print(i)

# 遍历字典
person = {"name": "张荣殿", "age": 30, "city": "北京"}
for key, value in person.items():
    print(f"{key}: {value}")

(2) while循环

while循环用于在条件为真时重复执行代码块:

count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1

# 使用break退出循环
count = 0
while True:
    print(f"Count: {count}")
    count += 1
    if count >= 5:
        break

# 使用continue跳过当前迭代
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)  # 打印奇数:1, 3, 5, 7, 9

五、函数

函数是组织好的、可重复使用的代码块,用于执行特定任务。

1. 函数定义

使用def关键字定义函数:

# 定义一个简单的函数
def greet():
    print("Hello, World!")

# 调用函数
greet()  # 输出:Hello, World!

# 带参数的函数
def greet_name(name):
    print(f"Hello, {name}!")

greet_name("张荣殿")  # 输出:Hello, 张荣殿!

# 带默认参数的函数
def greet_with_default(name="World"):
    print(f"Hello, {name}!")

greet_with_default()  # 输出:Hello, World!
greet_with_default("Python")  # 输出:Hello, Python!

# 带返回值的函数
def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # 输出:8

# 带多个返回值的函数
def get_person():
    return "张荣殿", 30, "北京"

name, age, city = get_person()
print(name, age, city)  # 输出:张荣殿 30 北京

2. 可变参数

Python支持可变参数,即不确定参数个数的情况:

# *args:接收任意数量的位置参数,作为元组传递
def sum_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_numbers(1, 2, 3))  # 6
print(sum_numbers(1, 2, 3, 4, 5))  # 15

# **kwargs:接收任意数量的关键字参数,作为字典传递
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="张荣殿", age=30, city="北京")

3. Lambda函数

Lambda函数是一种匿名函数,使用lambda关键字定义,通常用于简单的、一次性的函数:

# 定义Lambda函数
double = lambda x: x * 2
print(double(5))  # 10

# 在高阶函数中使用Lambda
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))  # [2, 4, 6, 8, 10]

# 过滤偶数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4]

# 计算列表元素的和
from functools import reduce
total = reduce(lambda x, y: x + y, numbers)  # 15

六、类和对象

Python是一种面向对象的编程语言,支持类和对象的概念。

1. 类的定义

使用class关键字定义类:

class Person:
    # 类属性(所有实例共享)
    species = "人类"

    # 初始化方法
    def __init__(self, name, age):
        # 实例属性
        self.name = name
        self.age = age

    # 实例方法
    def greet(self):
        print(f"Hello, 我是{self.name},今年{self.age}岁。")

    def update_age(self, new_age):
        self.age = new_age

2. 创建对象

# 创建Person类的实例
person1 = Person("张荣殿", 30)
person2 = Person("李四", 25)

# 访问实例属性
print(person1.name)  # "张荣殿"
print(person2.age)  # 25

# 访问类属性
print(person1.species)  # "人类"
print(Person.species)  # "人类"

# 调用实例方法
person1.greet()  # 输出:Hello, 我是张荣殿,今年30岁。
person2.update_age(26)
person2.greet()  # 输出:Hello, 我是李四,今年26岁。

3. 继承

继承允许创建一个新类(子类),继承现有类(父类)的属性和方法:

# 定义父类
class Animal:
    def __init__(self, name):
        self.name = name

    def make_sound(self):
        print("动物发出声音")

# 定义子类
class Dog(Animal):
    def __init__(self, name, breed):
        # 调用父类的初始化方法
        super().__init__(name)
        self.breed = breed

    # 重写父类方法
    def make_sound(self):
        print("汪汪汪")

    def fetch(self):
        print(f"{self.name}在追球")

class Cat(Animal):
    def make_sound(self):
        print("喵喵喵")

# 创建子类实例
dog = Dog("小黑", "拉布拉多")
cat = Cat("小白")

# 调用方法
dog.make_sound()  # 输出:汪汪汪
cat.make_sound()  # 输出:喵喵喵

dog.fetch()  # 输出:小黑在追球

4. 多态

多态是指不同类的对象对同一方法的不同实现:

def animal_sound(animal):
    animal.make_sound()

# 多态示例
animal_sound(dog)  # 输出:汪汪汪
animal_sound(cat)  # 输出:喵喵喵

七、模块和包

1. 模块

模块是一个包含Python代码的文件,用于组织相关的函数、类和变量。

(1) 创建模块

创建一个名为math_operations.py的文件:

# math_operations.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为零")
    return a / b

(2) 导入模块

# 导入整个模块
import math_operations

print(math_operations.add(3, 5))  # 8

# 导入特定函数
from math_operations import add, subtract

print(add(3, 5))  # 8
print(subtract(10, 3))  # 7

# 导入所有函数
from math_operations import *

print(multiply(2, 3))  # 6
print(divide(10, 2))  # 5

# 给模块起别名
import math_operations as mo

print(mo.add(3, 5))  # 8

2. 包

包是一个包含多个模块的目录,目录中必须包含一个名为__init__.py的文件(可以是空文件)。

(1) 创建包

假设我们有以下目录结构:

my_package/
    __init__.py
    math_operations.py
    string_operations.py

string_operations.py内容:

# string_operations.py
def reverse_string(s):
    return s[::-1]

def capitalize_string(s):
    return s.capitalize()

(2) 导入包

# 导入包中的模块
import my_package.math_operations

print(my_package.math_operations.add(3, 5))  # 8

# 导入特定模块
from my_package import string_operations

print(string_operations.reverse_string("Python"))  # nohtyP

# 导入模块中的特定函数
from my_package.string_operations import reverse_string

print(reverse_string("Hello"))  # olleH

# 给模块起别名
from my_package import math_operations as mo

print(mo.multiply(2, 3))  # 6

八、异常处理

异常处理用于捕获和处理程序运行时可能出现的错误:

# 基本的异常处理
try:
    x = int(input("请输入一个整数:"))
    y = 10 / x
    print(f"结果是:{y}")
except ValueError:
    print("输入错误,请输入一个有效的整数。")
except ZeroDivisionError:
    print("错误:除数不能为零。")
except Exception as e:
    print(f"发生了未知错误:{e}")
else:
    print("没有发生异常。")
finally:
    print("无论是否发生异常,都会执行这段代码。")

# 抛出异常
def check_positive_number(num):
    if num <= 0:
        raise ValueError("必须输入正数")
    return num

try:
    check_positive_number(-5)
except ValueError as e:
    print(f"错误:{e}")

九、文件操作

Python提供了丰富的文件操作功能:

1. 打开和关闭文件

# 打开文件(默认只读模式)
file = open("test.txt", "r")

# 读取文件内容
content = file.read()
print(content)

# 关闭文件
file.close()

# 使用with语句(自动关闭文件)
with open("test.txt", "r") as file:
    content = file.read()
    print(content)

2. 文件打开模式

模式 描述
r 只读模式(默认)
w 写入模式,会覆盖已有内容
a 追加模式,在文件末尾添加内容
x 创建模式,如果文件已存在则失败
b 二进制模式
t 文本模式(默认)
+ 读写模式

3. 读取文件

# 读取整个文件
with open("test.txt", "r") as file:
    content = file.read()
    print(content)

# 逐行读取
with open("test.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip()去除换行符

# 读取所有行到列表
with open("test.txt", "r") as file:
    lines = file.readlines()
    print(lines)

4. 写入文件

# 写入文本
with open("test.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("这是第二行文本。\n")

# 追加文本
with open("test.txt", "a") as file:
    file.write("这是追加的文本。\n")

# 写入列表
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("test.txt", "w") as file:
    file.writelines(lines)

十、其他基础知识点

1. 列表推导式

列表推导式是一种简洁创建列表的方法:

# 基本语法:[表达式 for 变量 in 迭代器 if 条件]

# 创建包含1-10平方的列表
squares = [x ** 2 for x in range(1, 11)]
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 过滤偶数
even_numbers = [x for x in range(1, 21) if x % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. 字典推导式

# 创建字典:{键表达式: 值表达式 for 变量 in 迭代器 if 条件}

# 创建1-5的平方字典
squares_dict = {x: x ** 2 for x in range(1, 6)}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 过滤奇数
even_dict = {x: x * 2 for x in range(1, 11) if x % 2 == 0}
print(even_dict)  # {2: 4, 4: 8, 6: 12, 8: 16, 10: 20}

3. 集合推导式

# 创建集合:{表达式 for 变量 in 迭代器 if 条件}

# 创建1-10平方的集合
squares_set = {x ** 2 for x in range(1, 11)}
print(squares_set)  # {64, 1, 4, 36, 100, 9, 16, 49, 81, 25}

# 去重
numbers = [1, 2, 2, 3, 4, 4, 5]
distinct = {x for x in numbers}
print(distinct)  # {1, 2, 3, 4, 5}

4. 生成器表达式

生成器表达式与列表推导式类似,但使用圆括号(),返回一个生成器对象,节省内存:

# 创建生成器表达式
squares_gen = (x ** 2 for x in range(1, 11))
print(squares_gen)  # <generator object <genexpr> at 0x...>

# 遍历生成器
for num in squares_gen:
    print(num)

# 生成器只可遍历一次
print(list(squares_gen))  # []

总结

本文详细介绍了Python的基础语法,包括变量和数据类型、运算符、控制流程、函数、类和对象、模块和包、异常处理、文件操作等内容。Python语法简洁明了,易于学习,同时功能强大,适用于各种应用场景。通过不断练习和实践,您将能够熟练掌握Python编程。


发布网站:荣殿教程(zhangrongdian.com)

作者:张荣殿