python基础语法
Python 是一种高级编程语言,具有清晰的语法和强大的功能,非常适合初学者和专业开发者。在这里,我将介绍一些 Python 的基础语法。
1. 注释
在 Python 中,可以使用 # 来添加单行注释。
# 这是一个注释
print("Hello, world!") # 打印 Hello, world!
复制
2. 变量和数据类型
可以通过赋值语句来定义变量。Python 支持多种数据类型,如整数、浮点数、字符串和布尔值。
a = 10 # 整数
b = 3.14 # 浮点数
c = "Hello" # 字符串
d = True # 布尔值
复制
3. 数据结构
Python 提供了多种内置数据结构,如列表、元组、字典和集合```python
列表
my_list = [1, 2, 3, 4, 5]
元组my_tuple = (1, 2, 3)
字典
my_dict = {“name”: “Alice”, “age”: 25}
集合
my_set = {1, 2, 3}
### 4. 控制结构#### 条件语句
使用 `if`,`elif` 和 `else` 进行条件判断。
```python
x
if x > 0:
print(" 是正数")
elif x < 0:
print("x 是负数")
else:
print("x 是零")
复制
循环
使用 for 和 while 循环可以遍历集合或重复执行。
for 循环
for i in range(5):
print(i)
# while 循环
count =0
while count < 5:
print(count)
count += 1
复制
5. 函数
def 关键字定义函数。
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
复制
6. 模块和导入
可以将代码分成多个模块,以便于管理使用 import 语句导入模块。
import mathprint(math.sqrt(16 # 输出 4.0
复制
7. 异常处理
使用 try 和 except 来处理异常。
try:
result =10 / 0
except ZeroDivisionError:
print("不能除以零")
finally:
print("这是最终执行的")
复制
8. 文件操作
可以使用 open() 函数来读写文件。
python
写文件
with open(“example.txt”, “w”) as file:
file.write(“Hello, world!”)
读文件
with open(“example.txt”, “”) as file:
content = file.read()
print(content)

浙公网安备 33010602011771号