Python基础语法练习
本文涵盖了 Python 基础编程中的多个重要概念,从简单的输出语句到运算符、字符串操作、变量赋值等都有涉及。
这些例子非常适合初学者学习和理解 Python 的基本语法。
1. Hello World
# 输出Hello World
print("Hello, World!")
2. 变量赋值
# 创建变量并赋值
name = "Python"
age = 30
height = 1.75
print(f"语言: {name}, 年龄: {age}, 版本: {height}")
3. 用户输入
# 获取用户输入
name = input("请输入您的姓名: ")
print(f"您好, {name}!")
4. 数据类型检查
# 检查数据类型
num = 42
text = "Hello"
flag = True
print(f"num的类型: {type(num)}")
print(f"text的类型: {type(text)}")
print(f"flag的类型: {type(flag)}")
5. 基本运算
# 基本数学运算
a = 10
b = 3
print(f"加法: {a + b}")
print(f"减法: {a - b}")
print(f"乘法: {a * b}")
print(f"除法: {a / b}")
print(f"整除: {a // b}")
print(f"取余: {a % b}")
print(f"幂运算: {a ** b}")
6. 字符串操作
# 字符串基本操作
text = "Python Programming"
print(f"原字符串: {text}")
print(f"转大写: {text.upper()}")
print(f"转小写: {text.lower()}")
print(f"字符串长度: {len(text)}")
print(f"替换: {text.replace('Python', 'Java')}")
7. 字符串格式化
# 字符串格式化的不同方法
name = "张三"
age = 25
score = 95.5
# 方法1: f-string
print(f"姓名: {name}, 年龄: {age}, 分数: {score:.1f}")
# 方法2: format方法
print("姓名: {}, 年龄: {}, 分数: {:.1f}".format(name, age, score))
# 方法3: %格式化
print("姓名: %s, 年龄: %d, 分数: %.1f" % (name, age, score))
8. 注释练习
# 这是单行注释
print("Hello") # 行末注释
"""
这是多行注释
可以写很多行
用于详细说明
"""
print("World")
9. 常量定义
# Python中的常量约定(使用大写字母)
PI = 3.14159
MAX_SIZE = 100
APP_NAME = "我的应用"
print(f"圆周率: {PI}")
print(f"最大尺寸: {MAX_SIZE}")
print(f"应用名称: {APP_NAME}")
10. 多变量赋值
# 多变量同时赋值
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")
# 交换变量值
x, y = 10, 20
print(f"交换前: x={x}, y={y}")
x, y = y, x
print(f"交换后: x={x}, y={y}")
11. 转义字符
# 转义字符的使用
print("第一行\n第二行") # 换行
print("制表符\t分隔")
print("引号: \"Hello\"")
print("反斜杠: \\")
print("回车: \r覆盖")
12. 原始字符串
# 原始字符串(r-string)
path = r"C:\Users\Documents\file.txt"
regex = r"\d+\w*"
print(f"文件路径: {path}")
print(f"正则表达式: {regex}")
13. 字符串切片
# 字符串切片操作
text = "Python Programming"
print(f"前6个字符: {text[:6]}")
print(f"后11个字符: {text[7:]}")
print(f"中间部分: {text[7:18]}")
print(f"每隔一个字符: {text[::2]}")
print(f"反转字符串: {text[::-1]}")
14. 字符串判断
# 字符串内容判断
text = "Python123"
print(f"是否为数字: {text.isdigit()}")
print(f"是否为字母: {text.isalpha()}")
print(f"是否为字母数字: {text.isalnum()}")
print(f"是否为小写: {text.islower()}")
print(f"是否为大写: {text.isupper()}")
15. 输入类型转换
# 输入数据类型转换
try:
age = int(input("请输入您的年龄: "))
height = float(input("请输入您的身高(米): "))
print(f"您今年{age}岁,身高{height}米")
except ValueError:
print("输入格式错误!")
16. 布尔运算
# 布尔运算和逻辑操作
a = True
b = False
print(f"a and b: {a and b}")
print(f"a or b: {a or b}")
print(f"not a: {not a}")
print(f"not b: {not b}")
# 比较运算
x, y = 5, 10
print(f"{x} > {y}: {x > y}")
print(f"{x} < {y}: {x < y}")
print(f"{x} == {y}: {x == y}")
print(f"{x} != {y}: {x != y}")
17. 成员运算符
# in 和 not in 运算符
text = "Hello World"
print(f"'Hello' in text: {'Hello' in text}")
print(f"'Python' in text: {'Python' in text}")
print(f"'Python' not in text: {'Python' not in text}")
numbers = [1, 2, 3, 4, 5]
print(f"3 in numbers: {3 in numbers}")
print(f"6 in numbers: {6 in numbers}")
18. 身份运算符
# is 和 is not 运算符
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(f"a == b: {a == b}") # 值相等
print(f"a is b: {a is b}") # 不是同一个对象
print(f"a is c: {a is c}") # 是同一个对象
x = None
print(f"x is None: {x is None}")
print(f"x is not None: {x is not None}")
19. 运算符优先级
# 运算符优先级示例
result1 = 2 + 3 * 4 # 乘法优先
result2 = (2 + 3) * 4 # 括号改变优先级
result3 = 2 ** 3 ** 2 # 幂运算从右到左
result4 = 2 ** (3 ** 2) # 明确优先级
print(f"2 + 3 * 4 = {result1}")
print(f"(2 + 3) * 4 = {result2}")
print(f"2 ** 3 ** 2 = {result3}")
print(f"2 ** (3 ** 2) = {result4}")
20. 简单计算器
# 简单的计算器程序
def simple_calculator():
try:
num1 = float(input("请输入第一个数字: "))
operator = input("请输入运算符 (+, -, *, /): ")
num2 = float(input("请输入第二个数字: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 != 0:
result = num1 / num2
else:
print("错误:除数不能为零!")
return
else:
print("错误:不支持的运算符!")
return
print(f"结果: {num1} {operator} {num2} = {result}")
except ValueError:
print("错误:请输入有效的数字!")
# simple_calculator() # 取消注释来运行