1.学习简单使用if条件测试(注意:for函数后面有冒号,if 和 else后面都有冒号)
输入:
bicycles = ["title" , "cannondale" , "redline"]
for bicycle in bicycles:
if bicycle == "cannondale": # “ = = ” 检查是否相等
print(bicycle.title())
else:
print(bicycle.lower())
if bicycles != "title": # “ != ” 检查是否不相等
print(" Please have a think! ")
bicycle_love = "title"
if bicycle_love in bicycles: #检查特定的值是否包含在列表中
print("Here it is, your lover, " + bicycle_love.title())
bicycle_hete = "bike"
if bicycle_hete not in bicycles: #检查特定的值是否不包含在列表中
print("Sorry, you can have a look of others.")
if bicycle_hete != "Bike":
print("True")
输出:
title
Cannondale
redline
Please have a think!
Here it is, your lover, Title
Sorry, you can have a look of others.
True
2.学习简单if语句
输入:
age = 14
if age >10:
print("You can come in.")
输出:
You can come in.
3.学习if-else语句
输入:
age = 8
if age >10:
print("You can come in.")
else:
print("Sorry,it is not fit for you. ")
输出:
Sorry,it is not fit for you.
4.学习if-elif-else语句
输入:
age = 6
if age <3:
price =10
elif age <18:
price =20
else:
price = 25
print("Your admission cost is $" + str(price) + ".")
输出:
Your admission cost is $20.
5.学习使用多个elif代码块
输入:
age = 30
if age < 3:
price = 10
elif age < 18:
price = 20
elif age < 45:
price = 30
elif age < 70:
price = 15
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
输出:
Your admission cost is $30.
6.省略else (if-elif后可以省略else语句)
输入:
age =80
if age < 3:
price = 10
elif age < 18:
price = 20
elif age < 45:
price = 30
elif age < 70:
price = 15
elif age >= 70:
price = 5
print("Your admission cost is $" + str(price) + ".")
输出:
Your admission cost is $5.
7.多个简单if语句同时使用与if-elif-else语句的区别:(1)多个简单if语句同时使用:适合同时满足多个条件的情况,不论前面if语句测试结果如何都会继续执行后面if语句;(2) if-elif-else语句:仅适合只有一个条件满足的情况,即遇到通过了的测试后,将跳过余下的测试,不再继续执行下去。
eg1:
输入:
names = ["lihao", "dalao", "suosuo"]
if "lihao" in names:
print("lihao".title())
if "zhonghua" in names:
print("zhonghua".title())
if "suosuo" in names:
print("suosuo".title())
print("All above pepole, congradulation to you.")
输出:
Lihao
Suosuo
All above pepole, congradulation to you.
eg2:
输入:
names = ["lihao", "dalao", "suosuo"]
if "lihao" in names:
print("lihao".title())
elif "zhonghua" in names:
print("zhonghua".title())
elif "suosuo" in names:
print("suosuo".title())
print("All above pepole, congradulation to you.")
输出:
Lihao
All above pepole, congradulation to you.