基本语法结构
Python使用缩进来定义代码块,而不是大括号。这是Python最显著的特点之一。
# 条件语句示例
if x > 10:
print("x大于10")
elif x > 5:
print("x大于5但小于等于10")
else:
print("x小于等于5")
Python中的缩进通常使用4个空格,这是PEP 8推荐的风格。虽然可以使用制表符,但不建议混合使用空格和制表符。
变量与数据类型
Python是动态类型语言,不需要显式声明变量类型。
- 整数(int): 如
42
, -10
- 浮点数(float): 如
3.14
, -0.001
- 字符串(str): 如
"hello"
, 'world'
- 布尔值(bool):
True
或 False
- 列表(list): 有序可变序列,如
[1, 2, 3]
- 元组(tuple): 有序不可变序列,如
(1, 2, 3)
- 字典(dict): 键值对集合,如
{"name": "Alice", "age": 25}
# 变量赋值示例
name = "Alice" # 字符串
age = 25 # 整数
height = 1.68 # 浮点数
is_student = True # 布尔值
运算符
Python支持多种运算符,包括算术、比较、逻辑和赋值运算符。
# 算术运算符
a = 10 + 5 # 加法
b = 10 - 5 # 减法
c = 10 * 5 # 乘法
d = 10 / 3 # 除法(结果为浮点数)
e = 10 // 3 # 整除
f = 10 % 3 # 取模
g = 10 ** 2 # 幂运算
# 比较运算符
x == y # 等于
x != y # 不等于
x > y # 大于
x < y # 小于
x >= y # 大于等于
x <= y # 小于等于
# 逻辑运算符
a and b # 与
a or b # 或
not a # 非
控制流
Python提供了多种控制流语句来管理代码执行顺序。
# for循环示例
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while循环示例
count = 0
while count < 5:
print(count)
count += 1
# break和continue
for i in range(10):
if i == 3:
continue # 跳过本次循环
if i == 7:
break # 终止循环
print(i)
函数定义
函数是组织和重用代码的基本方式。
# 简单函数
def greet(name):
"""返回问候语"""
return f"Hello, {name}!"
# 带默认参数的函数
def power(base, exponent=2):
"""计算幂"""
return base ** exponent
# 可变参数
def sum_all(*numbers):
"""计算任意数量数字的和"""
total = 0
for num in numbers:
total += num
return total
Python函数可以返回多个值,实际上是返回一个元组。例如:return x, y, z
。
异常处理
Python使用try-except块来处理异常。
try:
x = int(input("请输入一个数字: "))
result = 10 / x
except ValueError:
print("输入的不是有效数字!")
except ZeroDivisionError:
print("不能除以零!")
else:
print(f"结果是: {result}")
finally:
print("执行完毕")