练习代码
#练习 if语句的形式
foods = ["苹果","香蕉","梨子"]
print("我喜欢的食物分别是:")
for my_foods in foods:if my_foods == "香蕉":print(str(my_foods) + "-这是我最爱的食物!")else:print(my_foods)
"""以上第一次运行出现错误,原因if语句忘记加冒号: 程序报错!"""#练习 用if语句检查特定的值是否在列表中
foods = ["苹果","香蕉","梨子"]
foods_a = "杏子"
if foods_a in foods: #判断foods_a在不在foods列表中print("没错," + str(foods_a) + "是我喜欢的食物之一!")
else:print(str(foods_a) + "不在我的喜欢的食物清单中!")foods_b = "牛肉"
if foods_b not in foods: #not in 不在print("你没搞错吧,我们在说水果!")"""练习5-3 外星人颜色"""
alien_color = "green"
if alien_color == "green":print("你获得5个点!")
alien_color = "blue"
if alien_color != "green":print("None")#版本1:if-else
alien_color = "yellow"
if alien_color == "green":print("玩家因射杀外星人获得了5个点!")
else:print("玩家获得了10个点!")#版本2:if
alien_color = "yellow"
if alien_color == "green":print("玩家因射杀外星人获得了5个点!")
if alien_color != "green":print("玩家获得了10个点!")#if-elif-else结构
alien_color = "red"
if alien_color == "green":game = 5
elif alien_color == "yellow":game = 10
elif alien_color == "red":game = 15
else:game = 0
print("玩家获得点数:" + str(game))#人生的不同阶段
age = int(20)
if age < 2:jieguo = "婴儿"
elif age < 4:jieguo = "蹒跚学步"
elif age < 13:jieguo = "儿童"
elif age < 20:jieguo = "青少年"
elif age < 65:jieguo = "成年人"
else:jieguo = "老年人"
print("您正处于" + str(jieguo) + "阶段,加油!")#喜欢的水果
favorite_fruits = ["苹果","香蕉","葡萄"]
if "香蕉" in favorite_fruits:print("you really like bananas!")
if "苹果" in favorite_fruits:print("you really like bananas!")
if "葡萄" in favorite_fruits:print("you really like bananas!")
if "梨子" in favorite_fruits:print("you really like bananas!")
结果输出
我喜欢的食物分别是:
苹果
香蕉-这是我最爱的食物!
梨子
杏子不在我的喜欢的食物清单中!
你没搞错吧,我们在说水果!
你获得5个点!
None
玩家获得了10个点!
玩家获得了10个点!
玩家获得点数:15
您正处于成年人阶段,加油!
you really like bananas!
you really like bananas!
you really like bananas!
进程已结束,退出代码 0
学习小结
编写if语句让我想起了大学学习C语言的情景,现在理解起来比较容易,跟着做了几个练习,第一次运行出现错误,原因if语句忘记加冒号: 程序报错!这也是很多新手容易出现的问题。
判断条件超过2个:使用if-elif-else,例如练习人生的不同阶段
#人生的不同阶段
age = int(20)
if age < 2:
jieguo = “婴儿”
elif age < 4:
jieguo = “蹒跚学步”
elif age < 13:
jieguo = “儿童”
elif age < 20:
jieguo = “青少年”
elif age < 65:
jieguo = “成年人”
else:
jieguo = “老年人”
print(“您正处于” + str(jieguo) + “阶段,加油!”)
测试多个条件:if-if-if… 例如程序判断水果在不在列表中
favorite_fruits = [“苹果”,“香蕉”,“葡萄”]
if “香蕉” in favorite_fruits:
print(“you really like bananas!”)
if “苹果” in favorite_fruits:
print(“you really like bananas!”)
if “葡萄” in favorite_fruits:
print(“you really like bananas!”)
if “梨子” in favorite_fruits:
print(“you really like bananas!”)