编程助手学Python--Deepseek对Python基础语法的理解
以下是 Python 基础语法的总结
1. Python 标识符
- 标识符是变量、函数、类等的名称。
- 规则:
- 由字母、数字、下划线
_
组成。 - 不能以数字开头。
- 区分大小写。
- 不能使用 Python 关键字(如
if
,else
,for
等)。
- 由字母、数字、下划线
2. Python 关键字
-
Python 保留的关键字,不能用作标识符。
-
常见关键字:
if
,else
,for
,while
,def
,class
,import
等。 -
查看所有关键字:
import keyword print(keyword.kwlist)
3. 注释
-
单行注释:以
#
开头。# 这是一个单行注释
-
多行注释:用三引号
'''
或"""
包裹。''' 这是一个 多行注释 '''
4. 行与缩进
-
Python 使用缩进来表示代码块,通常用 4 个空格。
-
缩进不一致会导致
IndentationError
。if True: print("True") # 缩进正确 else: print("False") # 缩进正确
5. 多行语句
-
如果一行代码过长,可以使用反斜杠
\
换行。total = 1 + 2 + 3 + \ 4 + 5 + 6
-
在
[]
,{}
,()
中的多行语句不需要反斜杠。days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
6. 输入与输出
-
输入:使用
input()
函数。name = input("请输入你的名字:")
-
输出:使用
print()
函数。print("Hello,", name)
7. 变量与数据类型
-
变量不需要声明类型,直接赋值即可。
a = 10 # 整数 b = 3.14 # 浮点数 c = "Hello" # 字符串 d = True # 布尔值
-
常见数据类型:
- 数字:
int
,float
,complex
- 字符串:
str
- 布尔值:
bool
- 列表:
list
- 元组:
tuple
- 集合:
set
- 字典:
dict
- 数字:
8. 运算符
- 算术运算符:
+
,-
,*
,/
,//
(整除),%
(取余),**
(幂) - 比较运算符:
==
,!=
,>
,<
,>=
,<=
- 逻辑运算符:
and
,or
,not
- 赋值运算符:
=
,+=
,-=
,*=
,/=
9. 字符串
-
字符串可以用单引号
'
或双引号"
包裹。str1 = 'Hello' str2 = "World"
-
多行字符串用三引号
'''
或"""
。str3 = '''这是一个 多行字符串'''
-
字符串操作:
- 拼接:
+
- 重复:
*
- 索引:
str[0]
- 切片:
str[1:4]
- 拼接:
10. 条件语句
-
if
、elif
、else
用于条件判断。if a > b: print("a 大于 b") elif a == b: print("a 等于 b") else: print("a 小于 b")
11. 循环语句
-
for
循环:for i in range(5): print(i)
-
while
循环:while a > 0: print(a) a -= 1
12. 函数
-
使用
def
定义函数。def greet(name): print("Hello,", name) greet("Alice")
13. 模块与导入
-
使用
import
导入模块。import math print(math.sqrt(16)) # 输出 4.0
14. 异常处理
-
使用
try
、except
捕获异常。try: result = 10 / 0 except ZeroDivisionError: print("除数不能为零")
15. 文件操作
-
打开文件:
file = open("example.txt", "r") content = file.read() file.close()
-
使用
with
语句自动关闭文件:with open("example.txt", "r") as file: content = file.read()
以上是 Python 基础语法的核心内容,适合初学者快速掌握 Python 的基本用法。