欢迎光临
我们一直在努力

Python 语法及入门(超全超详细)

Python是一种解释型的高级编程语言,其设计哲学强调代码的可读性和简洁性。以下是对Python语法及入门的超全超详细代码讲解:

CSDN大礼包:《2025年最新全套学习资料包》免费分享

在这里插入图片描述

1. Python 基础语法

1.1 第一个Python程序

# 这是一个单行注释
print("Hello, World!") # 输出字符串

1.2 变量和数据类型

# 变量声明和赋值
name = "Alice" # 字符串
age = 25 # 整数
height = 1.75 # 浮点数
is_student = True # 布尔值

# 打印变量类型
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>

1.3 运算符

# 算术运算符
a = 10
b = 3
print(a + b) # 加法 13
print(a b) # 减法 7
print(a * b) # 乘法 30
print(a / b) # 除法 3.333…
print(a // b) # 整除 3
print(a % b) # 取余 1
print(a ** b) # 幂运算 1000

# 比较运算符
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False

# 逻辑运算符
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False

2. 控制流

2.1 条件语句

# if-elif-else 结构
score = 85

if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")

2.2 循环结构

# for 循环
for i in range(5): # 0到4
print(i)

for i in range(1, 6): # 1到5
print(i)

# while 循环
count = 0
while count < 5:
print(count)
count += 1

# break 和 continue
for num in range(10):
if num == 3:
continue # 跳过本次循环
if num == 8:
break # 终止循环
print(num)

3. 数据结构

3.1 列表 (List)

# 创建列表
fruits = ['apple', 'banana', 'cherry']
print(fruits[1]) # 访问元素 banana

# 修改列表
fruits[0] = 'orange'
print(fruits) # ['orange', 'banana', 'cherry']

# 列表方法
fruits.append('grape') # 添加元素
fruits.insert(1, 'mango') # 插入元素
fruits.remove('banana') # 删除元素
print(fruits) # ['orange', 'mango', 'cherry', 'grape']

# 列表切片
print(fruits[1:3]) # ['mango', 'cherry']

# 列表遍历
for fruit in fruits:
print(fruit)

3.2 元组 (Tuple)

# 创建元组
coordinates = (10, 20)
print(coordinates[0]) # 10

# 元组不可修改
# coordinates[0] = 15 # 会报错

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

3.3 集合 (Set)

# 创建集合
unique_numbers = {1, 2, 3, 2, 1} # 自动去重 {1, 2, 3}

# 集合操作
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a b) # 差集 {1, 2}

3.4 字典 (Dictionary)

# 创建字典
person = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}

# 访问字典值
print(person['name']) # Alice
print(person.get('age')) # 25

# 修改字典
person['age'] = 26
person['email'] = 'alice@example.com'

# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")

4. 函数

4.1 定义和调用函数

# 定义函数
def greet(name):
"""这是一个问候函数"""
return f"Hello, {name}!"

# 调用函数
message = greet("Alice")
print(message) # Hello, Alice!

# 默认参数
def power(base, exponent=2):
return base ** exponent

print(power(3)) # 9 (3的2次方)
print(power(3, 3)) # 27 (3的3次方)

4.2 返回值

# 多返回值
def min_max(numbers):
return min(numbers), max(numbers)

min_val, max_val = min_max([1, 2, 3, 4, 5])
print(f"最小值: {min_val}, 最大值: {max_val}")

4.3 匿名函数 (Lambda)

# 使用lambda定义简单函数
double = lambda x: x * 2
print(double(5)) # 10

# 在高阶函数中使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]

5. 文件操作

5.1 读写文件

# 写入文件
with open('example.txt', 'w') as file:
file.write("这是第一行\\n")
file.write("这是第二行\\n")

# 读取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)

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

5.2 JSON 文件处理

import json

# 写入JSON
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "hiking"]
}

with open('data.json', 'w') as file:
json.dump(data, file, indent=4)

# 读取JSON
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)

6. 面向对象编程

6.1 类和对象

# 定义类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
return f"Hello, my name is {self.name} and I'm {self.age} years old."

# 创建对象
person1 = Person("Alice", 25)
print(person1.greet())

# 继承
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id

def study(self):
return f"{self.name} is studying."

student1 = Student("Bob", 20, "S12345")
print(student1.greet())
print(student1.study())

6.2 特殊方法

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)

def __str__(self):
return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
print(v3) # Vector(6, 8)

7. 异常处理

# try-except 块
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
finally:
print("这段代码总是会执行")

# 捕获多个异常
try:
# 可能出错的代码
value = int("abc")
except ValueError:
print("无效的整数字符串")
except (TypeError, ZeroDivisionError):
print("类型错误或除以零")

# 自定义异常
class NegativeNumberError(Exception):
pass

def square_root(x):
if x < 0:
raise NegativeNumberError("不能计算负数的平方根")
return x ** 0.5

try:
print(square_root(1))
except NegativeNumberError as e:
print(e)

8. 模块和包

8.1 创建和使用模块

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

def subtract(a, b):
return a b

# main.py
import math_operations

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

8.2 使用标准库

import math
import random
from datetime import datetime

# 数学函数
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793

# 随机数
print(random.randint(1, 100)) # 1到100之间的随机整数

# 日期时间
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

9. 高级特性

9.1 列表推导式

# 普通列表
squares = []
for x in range(10):
squares.append(x**2)

# 列表推导式
squares = [x**2 for x in range(10)]
print(squares)

# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)

9.2 生成器

# 生成器函数
def countdown(n):
while n > 0:
yield n
n -= 1

# 使用生成器
for i in countdown(5):
print(i) # 5, 4, 3, 2, 1

# 生成器表达式
sum_of_squares = sum(x**2 for x in range(10))
print(sum_of_squares)

9.3 装饰器

def my_decorator(func):
def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()
"""
输出:
函数执行前
Hello!
函数执行后
"""

10. 常用内置函数

# map 和 filter
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x*2, numbers)) # [2, 4, 6, 8, 10]
evens = list(filter(lambda x: x%2 == 0, numbers)) # [2, 4]

# enumerate
for i, value in enumerate(['a', 'b', 'c']):
print(i, value) # 0 a, 1 b, 2 c

# zip
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")

# any 和 all
print(any([False, True, False])) # True
print(all([True, True, False])) # False

总结

以上是Python的基础语法和常用功能的详细介绍。Python的语法简洁明了,非常适合初学者入门。要掌握Python,最重要的是多实践,通过编写代码来巩固所学知识。

赞(0)
未经允许不得转载:171主机测评 » Python 语法及入门(超全超详细)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址