#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: Christal date: 2021/10/31
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
# 判断中且用and, 或者用or
age0=18
age1=20
if(age0>15) and (age1>20):
print("True")
else:
print('False')
#检查特定值是否包含在列表中
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings #运行后返回TRUE
#检查特定值是否不包含在列表中
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
#if-elif-else
age=12
if age<4:
print('Your admission cost is $0.')
elif age<18:
print('Your admission cost is $5.')
else:
print('Your admission cost is $10.')
#做如下修改,更实用 (易修改,易移植)
age=22
if age < 4:
price = 0
elif age < 18:
price = 5
else:
price =10
print("Your admission cost is $" + str(price) + ".")
# 也可以不用else
age=22
if age < 4:
price = 0
elif age < 18:
price = 5
elif age>= 18:
price=10
print("Your admission cost is $" + str(price) + ".")
#只想执行一个代码块,使用if-elif-else结构;如果要运行多个代码块,就使用一系列独立的if语句
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!")
#缺少配料green peppers
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding" + requested_topping +".")
print("\nFinished making your pizza!")
# 不添加任何东西
requested_toppings=[]
#requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print("Adding " + requested_topping + ". ")
print("\nFinished making your pizza!")
else:
print("Are you want a plain pizza?")
#判断客户要求是否满足
available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni',
'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese'] # requested_toppings=[]
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping +'.')
else:
print("Sorry, we do not have "+ requested_topping+ '.')
print("\nFinished making your pizza!")
print("Are you want a plain pizza?")
Python 3 《if》入门练习
最新推荐文章于 2023-09-07 09:36:48 发布