if 分支语句

比较三个数中最大的一个

a=float(input("a="))
b=float(input("b="))
c=float(input("c="))
my_max=a>b and a or b
my_max=c>b and c or my_max
print(my_max)

说明:条件成立取 and后的值,条件不成立取or 后面的值。


import math
….
print(max(a,b,c))

计算个人所得税

salary=float(input("本月收入:"))
insurance=float(input("五险一金:"))
diff=salary-insurance-3500
if diff<=0:
    tax=o
    deducation=0
elif diff<=1500:
    rate=0.03
    deducation=0
elif diff<=4500:
    tax=0.1
    deducation=105
elif diff<9000:
    tax=0.2
    deducation=555
elif diff<=35000:
    tax=0.25
    deducation=1005
elif diff<=55000:
    rate=0.3
    deducation=2755
elif diff<=85000:
    rate=0.35
    deducation=5505
else:
    rate=0.45
    deducation=13505
p=diff*rate-deducation
print("个人应交税为:%.3f"%p)

<think>我们首先讲解Python中的if分支语句if语句用于条件判断,根据条件的真假执行不同的代码块。 基本结构: if 条件1: 执行语句1 elif 条件2: # 可选,可以有0个或多个elif 执行语句2 else: # 可选,可以有0个或1个else 执行语句3 注意:每个条件后面都要有冒号,并且执行语句需要缩进(通常4个空格)。 示例1:最简单的if语句 示例2:if-else语句 示例3:if-elif-else语句 下面我们通过几个例子来详细说明。</think>### Python中的if分支语句 if语句是Python中的核心条件控制结构,用于根据条件真假执行不同的代码块。以下是详细说明和示例: #### 基本语法结构 ```python if 条件1: # 条件1为真时执行 elif 条件2: # 可选(0或多个) # 条件2为真时执行 else: # 可选(0或1个) # 所有条件都不满足时执行 ``` #### 示例代码 ```python # 示例1:基本if判断 age = 18 if age >= 18: print("您已成年,可以进入") # 示例2:if-else结构 temperature = 25 if temperature > 30: print("开启空调") else: print("关闭空调") # 示例3:多条件判断(if-elif-else) score = 85 if score >= 90: grade = 'A' elif score >= 80: grade = 'B' # 此条件会被执行 elif score >= 70: grade = 'C' else: grade = 'D' print(f"成绩等级: {grade}") # 示例4:嵌套if语句 is_member = True purchase = 1200 if is_member: if purchase > 1000: discount = 0.8 else: discount = 0.9 else: discount = 1.0 print(f"折扣率: {discount}") # 示例5:复合条件(and/or) username = "admin" password = "123456" if username == "admin" and password == "123456": print("登录成功") else: print("用户名或密码错误") ``` #### 关键特性说明: 1. **缩进规则**:Python使用缩进(通常4个空格)定义代码块,这是语法强制要求 2. **条件表达式**: - 比较运算符:`==`, `!=`, `>`, `<`, `>=`, `<=` - 逻辑运算符:`and`, `or`, `not` - 成员检查:`in`, `not in` 3. **真值判断**: - 视为False的值:`False`, `None`, `0`, `""`, `[]`, `()`, `{}` - 其他值均视为True 4. **三元表达式**:简化版if-else ```python max_value = x if x > y else y # 取x和y中的较大值 ``` #### 最佳实践: 1. 避免深层嵌套(超过3层考虑重构) 2. 复杂条件拆分为临时变量 ```python is_valid_user = (user.active and user.role in ["admin", "editor"]) if is_valid_user: ... ``` 3. 使用括号明确复杂逻辑优先级 ```python if (a > b and c != 0) or d == 1: ... ``` #### 常见错误: 1. 忘记冒号`:`结尾 2. 错误缩进导致逻辑错误 3. 混淆赋值`=`和比较`==` 4. 多个条件未使用逻辑运算符连接 ```python # 错误写法 if 10 < age < 20: # 正确:链式比较 if age > 10 and < 20: # 错误写法 ``` if语句是编程中最基础的控制流工具,掌握其使用对编写逻辑清晰的代码至关重要。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值