Python 基础语法详解
1. Jupyter Notebook 简单操作
Jupyter Notebook 是常用的交互式编程环境。以下是常用快捷键:
- dd: 删除当前行 (delete)
- Shift + Enter: 运行当前单元格并移动光标
- Ctrl + Enter: 运行当前单元格
- M: 将单元格转换为 Markdown 模式
- Y: 将单元格转换为代码模式
2. print() 用法
print(1)
print('yi')
print("i'm")
print('i\'m')
print('a'+'b')
输出:
1
yi
i'm
i'm
ab
3. 数学运算示例
# 幂运算
result = 2**3
print(result) # 8
4. 循环控制与缩进
Python 使用缩进(通常为 4 个空格)来划分代码块。
# While 循环
i = 0
while i < 3:
print(i)
i += 1
# For 循环
for i in range(1, 5):
print(i)
输出: 0 1 2 1 2 3 4
5. 条件判断语句
a = 5
b = 3
if a > b:
print('a 大于 b')
if a > b:
print('a 大于 b')
else:
print('a 小于等于 b')
if a > b:
print('a 大于 b')
elif a == b:
print('a 等于 b')
else:
print('a 小于 b')
注意:比较运算符使用 ==,赋值使用 =。
6. 函数定义
基本格式
def add(a, b):
x = a + b
print(x)
add(3, 4) # 输出:7
默认参数
def default_fun(a, b=3):
x = a + b
print(x)
default_fun(2) # 输出:5
注意: 默认参数必须放在非默认参数之后,否则会报错 SyntaxError: non-default argument follows default argument。
7. 文件操作
创建并写入文件
text = "1,2,3"
file = open('text.txt', 'w')
file.write(text)
file.close()
追加写入
append = "\nhello world"
file = open('text.txt', 'a')
file.write(append)
file.close()
读取文件
with open('text.txt', 'r') as file:
content = file.read()
print(content)
推荐使用 with 语句自动管理文件资源。
8. 类与对象
class Calculator:
price = 18
brand = "casio"
def __init__(self, name='e', price=8, brand='u', size=7):
self.name = name
self.price = price
self.brand = brand
self.size = size
def add(self, x, y):
result = x + y
print(result)
def show(self):
print(self.name, self.price, self.brand, self.size)
# 实例化
calc1 = Calculator()
calc1.add(3, 5) # 输出:8
calc1.show() # 输出:e 8 u 7
self 代表实例本身,类似于其他语言中的 this。
9. input 函数
a = input()
if a == '1':
print('yes')
else:
print('no')
注意: input() 返回的是字符串类型,如需数值需进行类型转换(如 int(input()))。
10. 列表与元组
列表操作
a_list = [7, 6, 5, 4, 3, 2]
a_list.append('a')
a_list.insert(3, 'h')
a_list.remove('h')
print(a_list[-1]) # 最后一个元素
print(a_list[2:4]) # 切片
print(a_list.index('a')) # 查找索引
b_list = [1, 8, 5, 8, 9, 2]
b_list.sort() # 升序
b_list.sort(reverse=True) # 降序
元组
元组是不可变序列。
a_tuple = (1, 2, 3, 4, 5, 6)
for item in a_tuple:
print(item)
多维列表
multi_list = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(multi_list[0][0]) # 输出:1
11. 字典
diction = {'key1': 'value1', 'key2': 'value2'}
print(diction['key2'])
del diction['key2']
print(diction)
字典的 value 可以是任意数据类型。
12. 模块导入
import time as t
print(t.localtime())
13. 流程控制语句
Break 与 Continue
# Break 终止循环
while True:
b = input()
if b == '1':
print('end')
break
else:
print('go on')
# Continue 跳过本次迭代
while True:
b = input()
if b == '1':
print('end')
continue
else:
print('go on')
14. 高阶函数
Zip
a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b))) # [(1, 4), (2, 5), (3, 6)]
Lambda 表达式
plus = lambda x, y: x + y
print(plus(2, 6)) # 8
Map
nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9]
15. 异常处理
在程序运行时捕获错误,防止程序崩溃。
try:
num = int(input("请输入数字:"))
result = 10 / num
print(f"结果是:{result}")
except ValueError:
print("输入无效,请输入整数")
except ZeroDivisionError:
print("不能除以零")
finally:
print("执行完毕")
16. 列表推导式
用于简洁地创建列表。
squares = [x**2 for x in range(10)]
print(squares)
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
17. 上下文管理器
使用 with 语句确保资源被正确关闭。
with open('data.txt', 'w') as f:
f.write('Hello World')
# 文件在此处自动关闭
18. 装饰器
装饰器是一种修改函数行为的工具。
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
本文涵盖了 Python 核心语法的基础到进阶部分,包括变量、控制流、函数、面向对象、文件操作及常用内置功能。掌握这些内容是学习数据分析、Web 开发或人工智能的前提。

