Python3 基础学习笔记第四章 —— 【if语句】
- 4.1 一个简单的数列
给定一个汽车列表,将其中每一辆汽车的名称打印出来,要求打印 ‘bmw’ 时所有字母都要大写,其余名称只需要首字母大写:
1 | cars = ['audi' , 'bmw' , 'subaru' , 'toyota'] |
输出结果如下:
1 | Audi |
- 4.1.1 检查特定值是否包含在列表当中
要判断特定的值是否已包含在列表当中,可使用关键字 in
1 | user_names = ['andia' , 'david' , 'liwa'] |
输出结果如下:
1 | Andiais in user_name. |
要判断特定的值是否不包含在列表当中,可使用关键字 not in
1 | user_names = ['andia' , 'david' , 'liwa'] |
输出结果如下:
1 | Kivleis not in user_name. |
- 4.2 if-else 语句
1 | age = input("请输入你的年龄查看是否可以去网吧:") |
分别输入19和15,输出结果如下:
1 | 请输入你的年龄查看是否可以去网吧:19 |
1 | 请输入你的年龄查看是否可以去网吧:15 |
- 4.3 if-elif-else 结构
1 | age = 12 |
输出结果如下:
1 | Your admission cost is $5. |
- 4.3.1 使用多个 elif 代码块
1 | age = 20 |
输出结果如下:
1 | Your admission cost is $15. |
- 4.3.2 省略 else 代码块
Python并不要求 if-elif 结构后面必须有 else 代码块:
1
2
3
4
5
6
7
8
9
10age = 20
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 15
elif age >= 65:
price = 10
print("Your admission cost is $" + str(price) + ".")
输出结果仍与3.3.1一样
- 4.4 测试多个条件
if-elif-else结构功能强大,但仅适用于只有一个条件满足的情况:遇到通过了的测试后,Python就会跳过余下的测试:
1 | names = ['Zhangshan' , 'Wanger'] |
输出结果如下:
1 | Zhangshan is here! |
相同的程序,如果使用 if-elif-else 结构,代码将不能正确运行:
1 | names = ['Zhangshan' , 'Wanger'] |
输出结果如下:1
2Zhangshan is here!
All the students are here!
- 4.5 使用 if 语句处理列表
- 4.5.1 检查特殊元素
对3.4例子改版,加入姓名 ‘Xiaoming’,当检索到Xiaoming时告诉他,他妈妈叫他回家吃饭1
2
3
4
5
6
7names = ['Zhangshan' , 'Wanger' , 'Xiaoming']
for name in names:
if name == 'Xiaoming':
print("Xiaoming,Your mother told you to go home for dinner!")
else:
print(name +"is here!")
print("All the students are here!")
输出结果如下:
1 | Zhangshanis here! |
- 4.5.2 确定列表不是空的
在检索姓名前检查姓名是否为空,不为空则打印出所有姓名,为空则提示没有姓名:
1 | names = [] |
输出结果如下:
1 | There is no students! |
- 4.5.3 使用多个列表
两个列表names_1和names_2,要求输出既在names_2中又在names_1中的元素:
1 | names_1 = ['Zhangshan' , 'Liyang' , 'Wanger' , 'Tangyang' , 'Xiaoming'] |
输出结果如下:
1 | Liyang is here! |