- # if 语句与 for 循环语句, 这个模式在实际编程中经常用
- cars = ['audi','bmw','subaru','toyota']
- for car in cars:
- if car == 'bmw':
- print(car.upper())
- else:
- print(car.title())
程序 2 :if 语句
- # if 语句
- age =7;
- if age>=18:
- print("You are old enough to vote!")
- # if 与 else
- if age>=18:
- print("You are old enough to vote!")
- else:
- print("Sorry,you are too young to vote.")
程序 3 : 使用多个 elif 代码块
- # 使用多个 elif 代码块
- age = 12
- if age<4:
- price = 0
- elif age<18:
- price = 5
- elif age<65:
- price=10
- else:
- price =5
- print("Your admission cost is $"+str(price)+".")
程序: 4: 省略 else 代码块
- '''else 是一条包罗万象的语句, 只要不满足任何 if 或 elif 中的条件测试, 其中的代码就会执行, 这可能会引入无效甚至恶意的数据. 如果知道最终要测试的条件, 应考虑使用
- 一个 elif 代码块来代替 else 仅当满足相应的条件时, 你的代码才会执行.'''
- # 省略 else 代码块
- age = 98
- if age<4:
- price = 0
- elif age<18:
- price = 5
- elif age<65:
- price=10
- elif age>=65:
- price =5
- print("Your admission cost is $"+str(price)+".")
程序 6:if 语句下嵌套 for 循环
- '''在这里, 我们首先创建了一个空列表, 其中不包含任何配料. 在处我们进行了简单检查, 而不是直接执行 for 循环. 在 if 语句中将列表名用在条件表达式中
- 时, Python 将在列表至少包含一个元素时返回 True , 并在列表为空时返回 False . 如果 requested_toppings 不为空, 就运行与前一个示例相同的 for 循环; 否则, 就打印
- 一条消息, 询问顾客是否确实要点不加任何配料的普通比萨'''
- requests =[]
- if requests:
- for request in requests:
- print("Adding"+request+".")
- print("\nFinished making your pizza")
- else:
- print("Are you sure you want a plain pizza")
程序 7: 多个列表, 这种形式的在实际编码中也常见
- # 多个列表, 这种形式的在实际编码中也常见
- available_toppings = {'mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'}
- requested_toppings = {'mushrooms','french fries','extra cheese'}
- for requested_topping in requested_toppings:
- if requested_topping in available_toppings:
- print("Adding"+requested_topping+".")
- else:
- print("Sorry,we don't have "+requested_topping)
- print("\nFinished making your pizza")
来源: http://www.bubuko.com/infodetail-2894107.html