在编程入门阶段,掌握常量、变量和运算符是构建逻辑思维的基石。Python以其简洁的语法和直观的语法规则,成为初学者的首选语言。本文将从基础概念出发,通过代码示例和实战场景,带您快速掌握Python核心语法要素。
常量是程序运行中值不可改变的数据,Python中通过全大写命名约定表示常量(虽无强制约束,但为行业通用规范):
python
1PI = 3.1415926 # 数学常量π 2GRAVITY = 9.8 # 重力加速度(单位:m/s²) 3MAX_CONNECTIONS = 100 # 最大连接数
命名规则:
_)。1_PI非法)。if、
for等)。
python
1# 计算圆的面积
2radius = 5
3area = PI * radius ** 2 # 使用常量PI
4print(f"半径为{radius}的圆面积为{area:.2f}") # 输出:半径为5的圆面积为78.54<"www.heshan.gov.cn.a-8.cn">
Python变量无需声明类型,直接赋值即可创建:
python
1age = 25 # 整数类型 2name = "Alice" # 字符串类型 3is_student = True # 布尔类型 4height = 1.75 # 浮点数类型
动态类型特性:同一变量名可重新赋值为不同类型:
python
1temperature = 36.5 # 浮点数 2temperature = "36.5℃" # 重新赋值为字符串
user_name、
total_price。i、
x适用于循环计数器。student_count比
n<"www.enping.gov.cn.a-8.cn">更易理解。错误示例:
python
12nd_place = "Bob" # 数字开头非法 2user-name = "Alice" # 连字符非法(应使用下划线)
Python支持链式赋值和序列解包:
python
1# 链式赋值 2x = y = z = 10 # x、y、z均为10 3<"www.lianjiang.gov.cn.a-8.cn"> 4# 序列解包 5a, b, c = 1, 2, 3 # a=1, b=2, c=3 6coordinates = (4, 5) 7x, y = coordinates # x=4, y=5
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
+ |
加法 |
5 + 3 |
8 |
- |
减法 |
10 - 4 |
6 |
* |
乘法 |
2 * 7 |
14 |
/ |
除法 |
15 / 4 |
3.75 |
// |
整除 |
15 // 4 |
3 |
% |
取模 |
15 % 4 |
3 |
** |
幂运算 |
2 ** 3 |
8 |
实战案例:计算商品折扣价
python
1original_price = 199.99
2discount_rate = 0.8 # 8折
3final_price = original_price * discount_rate # 159.992
4print(f"折后价:{final_price:.2f}元") # 输出:折后价:159.99元
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
== |
等于 |
5 == 5 |
True |
!= |
不等于 |
5 != 3 |
True |
> |
大于 |
10 > 7 |
True |
< |
小于 |
2 < 4 |
True |
>= |
大于等于 |
5 >= 5 |
True |
<= |
小于等于 |
3 <= 2 |
False |
应用场景:用户登录验证
python
1stored_password = "python123"
2input_password = input("请输入密码:")
3if input_password == stored_password:
4 print("登录成功!")
5else:<"www.leizhou.gov.cn.a-8.cn">
6 print("密码错误!")
| 运算符 | 描述 | 示例 | 结果 |
|---|---|---|---|
and |
与 |
True and False |
False |
or |
或 |
True or False |
True |
not |
非 |
not True |
False |
实战案例:判断年份是否为闰年
python
1year = 2024
2is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
3print(f"{year}年是闰年:{is_leap}") # 输出:2024年是闰年:True
简化代码的快捷方式:
python
1count = 10 2count += 5 # 等价于 count = count + 5 → count=15 3count *= 2 # 等价于 count = count * 2 → count=30 4count //= 3 # 等价于 count = count // 3 → count=10
python
1# 获取用户输入
2num1 = float(input("请输入第一个数字:"))
3operator = input("请输入运算符(+、-、*、/):")
4num2 = float(input("请输入第二个数字:"))
5
6# 计算结果
7if operator == "+":
8 result = num1 + num2
9elif operator == "-":
10 result = num1 - num2
11elif operator == "*":
12 result = num1 * num2
13elif operator == "/":
14 if num2 != 0:<"www.wuchuan.gov.cn.a-8.cn">
15 result = num1 / num2
16 else:
17 result = "错误:除数不能为零!"
18else:
19 result = "错误:无效运算符!"
20
21# 输出结果
22print(f"结果:{result}")
变量未定义错误:
python
1print(x) # 报错:NameError: name 'x' is not defined
解决:确保变量已赋值后再使用。
类型错误:
python
1result = "5" + 3 # 报错:TypeError: can only concatenate str (not "int") to str
解决:统一类型(如
result = int("5") + 3)。
使用调试工具:
print()语句检查变量值。掌握常量、变量和运算符后,您已具备编写简单程序的能力。下一步可学习:
if-elif-else、
for/
while循环。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3100113/ ,如需转载,请注明出处,否则将追究法律责任。