阅读更多
####if语句###
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car=='bmw': #==检查是否相等 即相等时返回Ture,不相等时返回Flase
print(car.upper())
else:
print(car.title())
cars=['audi','bmw','subaru','toyota']
for car in cars:
if car !="bmw": #!=检查是否不相等 即不相等时返回Ture,相等时返回Flase
print(car.upper())
else:
print(car.lower())
#补python终端检查是否相等
#>>>car='bmw'
#>>>car=='bmw'则输出Ture 否则返回Flase, !=同理
#if例子
#检查一个人是否是20岁(单个条件)
answer=18
if answer!=20: #当然条件可以是大于小于等等 <,>,<=,>=,等等
print('That id not the correct answer,Please try again!')
#检查多个条件 and ###关键字or与and类似 不予列举
answer=18
if answer>=17 and answer<=20:
print('That id not the correct answer,Please try again!')
#灵活运用 可对多个人进行检查
answer_1=18
answer_2=20
if answer_1>=16 and answer_1<=20 and answer_2<30:
print('That id not the correct answer,Please try again!')
##检查特定值是否在列表中:可利用python终端来执行##
#1.>>>cars=['audi','bmw','subaru','toyota']
#>>>"bmw" in cars
#2.
cars=['audi','bmw','subaru','toyota']
car='bmw'
if car in cars: #in前加not即没有在列表内
print(car.title()+' '+"in the list")
######
#if-elif-else结构 ##只能测试指定一个条件(通过一个测试条件将跳过余下的测试)#
#可根据需要使用任意数量的elif代码块
age=15
if age<4:
price=0 #print("Your admission cost is $0")
elif age<18:
price=5 #print("Your admission cost is $5")
else:
price=10 #print("Your admission cost is $10")
print("Your admission cost is $"+str(price)+".")#str()函数:将某一个类型强制转换为字符串型。如,a = 1,a的类型就是数值型,a = str(a),a就是字符串型了
##测试多个条件
print('\n')
requested_toppings=['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
print("Finished making your pizza!")
#与for循环连用 (检查列表元素中有无特殊元素)
#披萨店满足顾客的单个条件
print('\n')
requested_toppings=['mushrooms','extra cheese','pepperoni','green pappers']
for requested_topping in requested_toppings:
if requested_topping=='pepperoni':
print("Sorry,we are out of pepperoni right now.")
else:
print('Adding '+requested_topping+'.')
print('Finished making your pizza!')
#披萨店满足顾客的多个条件
print('\n')
available_toppings=['mushrooms','extra cheese','pepperoni','green pappers','olives']
requested_toppings=['mushrooms','extra cheese','pineapple']
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('\n')
requested_toppings=[]
if requested_toppings: #如果该列表为空时返回False;至少有一个元素时返回True,进行下面的for循环
for requested_topping in requested_toppings:
print('Adding '+requested_topping+'.')
else:
print("Are you sure you want a plain pizza?")
更多文章、技术交流、商务合作、联系博主
微信扫码或搜索:z360901061
微信扫一扫加我为好友
QQ号联系: 360901061
您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。
【本文对您有帮助就好】元