if语句代码pyhon
时间: 2025-04-18 14:49:47 浏览: 25
### Python 中 `if` 语句的用法
#### 条件判断基础
在Python中,`if` 语句用于执行基于条件测试的结果来决定是否运行某段代码。当指定的条件为真时,则执行紧跟其后的代码块;如果条件不成立则跳过该部分[^1]。
```python
x = 10
if x > 5:
print("x is greater than five.")
```
#### 多重条件判断
除了基本形式外,还可以通过加入 `elif` 和 `else` 关键字来进行更复杂的多分支选择结构。这允许程序根据不同的情况采取相应的行动。
```python
grade = 88
if grade >= 90:
letter_grade = 'A'
elif grade >= 80:
letter_grade = 'B'
elif grade >= 70:
letter_grade = 'C'
else:
letter_grade = 'F'
print(f"The student's grade is {letter_grade}.")
```
#### 结合逻辑运算符
利用逻辑运算符可以构建更加精细的条件表达式。值得注意的是,在涉及多个布尔表达式的组合时,由于Python支持短路求值机制,因此并非所有的子表达都会被执行[^2]。
```python
a, b = True, False
result = a and b or not b # 只有当b为False时才会计算not b这部分
print(result)
```
#### 实际应用场景实例
下面给出一个实际应用的例子:模拟简单的用户认证过程。这里设定了固定的用户名和密码,并给予三次尝试机会给用户输入正确的凭证信息[^3]。
```python
correct_name = 'root'
correct_passwd = 'westos'
attempts_left = 3
while attempts_left > 0:
name = input('Enter your username:')
passwd = input('Enter your password:')
if name == correct_name and passwd == correct_passwd:
print("Login successful!")
break
else:
attempts_left -= 1
if attempts_left != 0:
print(f"Incorrect credentials. You have {attempts_left} attempt(s) left.")
else:
print("Too many failed login attempts.")
```
阅读全文
相关推荐

















