跳到主要内容 Python 基础语法详解 | 极客日志
Python AI 算法
Python 基础语法详解 Python 基础语法涵盖了从环境操作到核心编程概念的关键内容。文章介绍了 Jupyter Notebook 的常用快捷键,详细讲解了变量定义、数据类型(整数、字符串、列表、元组、字典)、控制流语句(if-else、while、for)。此外,还深入阐述了函数的定义与参数传递、类的创建与面向对象编程、文件读写操作以及模块导入方法。补充了异常处理、列表推导式和上下文管理等进阶基础,帮助初学者建立完整的 Python 知识体系,为后续学习数据分析或自动化脚本打下坚实基础。
宁静 发布于 2025/2/6 更新于 2026/4/21 2 浏览
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' )
3. 数学运算示例
result = 2 **3
print (result)
4. 循环控制与缩进 Python 使用缩进(通常为 4 个空格)来划分代码块。
i = 0
while i < 3 :
print (i)
i += 1
for i in range (1 , 5 ):
print (i)
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 )
默认参数 def default_fun (a, b=3 ):
x = a + b
print (x)
default_fun(2 )
注意: 默认参数必须放在非默认参数之后,否则会报错 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)
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 )
calc1.show()
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 ])
11. 字典 diction = {'key1' : 'value1' , 'key2' : 'value2' }
print (diction['key2' ])
del diction['key2' ]
print (diction)
12. 模块导入 import time as t
print (t.localtime())
13. 流程控制语句
Break 与 Continue
while True :
b = input ()
if b == '1' :
print ('end' )
break
else :
print ('go on' )
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)))
Lambda 表达式 plus = lambda x, y: x + y
print (plus(2 , 6 ))
Map nums = [1 , 2 , 3 ]
squared = list (map (lambda x: x**2 , nums))
print (squared)
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 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 开发或人工智能的前提。
相关免费在线工具 加密/解密文本 使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
RSA密钥对生成器 生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
Mermaid 预览与可视化编辑 基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
curl 转代码 解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
Base64 字符串编码/解码 将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
Base64 文件转换器 将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online