ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

if语句

2021-11-16 10:36:24  阅读:181  来源: 互联网

标签:语句 requested topping age else toppings print


第4节.if语句

4.1 if语句的简单示例

cars=['audi','bmw','subaru','toyota']
for car in cars:
   if car=='bmw':
       print(car.upper())
   else:
       print(car.title())

4.2 if语句

if-else语句

age=17
if age>=18:
   print("You are old enough to vote!")
   print("Have you registered to vote yet?")
else:
   print("Sorry,you are too young to vote.")
   print("Please register to vote as soon as you turn 18!")

if-elif-else结构

用于检查超过两个的情形

'''
我们以一个根据年龄收费的游乐场为例:
4岁以下免费
4~18岁收费25美元
18(含)岁以上收费40美元
'''
age=12
if age <4:
   print("Your admission cost is $0")
elif age < 18:                #只会执行通过测试的代码
   print("Your admission cost is $25")
else:
   print("Your admission cost is $40")
#现在我们将上面的代码进行简化
age =12
if age <4:
   price=0
elif age <18:
   price=25
else:
   price=40
print(f"Your admission cost is ${price}.")
#else代码块可以省略,只要不满足if或elif的测试条件,else中的代码就会执行
#如果知道最终要测试的条件,就可以考虑用一个elif代码块代替else代码块
#if-elif-else结构功能强大,但仅适合用于只有一个条件满足的情况,遇到了通过测试的情况,剩下的代码就会跳过执行

测试多个条件

requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
   print('Adding mushrooms.')
if 'pepperoni' in requested_toppings:
   print('Adding pepperoni.')
if 'extra cheese' in requested_toppings:
   print('Adding extra cheese.')
print("\nFinished making your pizza!")
#首先创建一个列表,然后依次检查某一元素是否在列表中最后输出结果
#如果只想执行一个代码块,就是用if-elif-else结构;如果要执行多个代码块,使用一系列独立的if语句

4.3使用if语句检查列表

检查特殊元素

requested_toppings=['nushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
   if requested_topping == 'green peppers':
       print("Soory we are out of green peppers!")
   else:
       print(f"Adding {requested_topping}")
print(f"\nFinished making your pizza!")

确定列表不是空的

运行for循环前确定列表是否为空很重要

requested_toppings=[]
if requested_toppings:
   for requested_topping in requested_toppings:
       print(f"Adding {requested_topping}")
   print ("\nFinished making your piaaz!")
else:
   print("Are you sure want a plain pizza?")

使用多个列表:

available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings = ['mushrooms','french fris','extra cheese']
for requested_topping in requested_toppings:
   if requested_topping in available_toppings:
       print(f"Adding {requested_topping}")
   else:
       print(f"Sorry,we don't have {requested_topping}")
print("\nFinished making your pizza!")

 

标签:语句,requested,topping,age,else,toppings,print
来源: https://www.cnblogs.com/caujie/p/15559862.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有