您的位置:首页 > 编程语言 > Python开发

Python学习_我要使用if判断语句

2017-11-15 15:22 519 查看
我在需要区分不同条件下的不同情况时,需要使用到if语句

1、第一个if语句

我有apple、pear、peach、banana等一些水果,要求水果为pear时,全部大写打印,其他水果要求首字母大写打印

fruits=('apple','pear','peach','banana')
for fruit in fruits:
if fruit!='pear':
print(fruit.title())
else:
print(fruit.upper())


输出:

Apple

PEAR

Peach

Banana

2、我需要检查元素是否在列表中

如我需要检查banana是否在列表中以确定我能够购买,可以使用 in

fruits=('apple','pear','peach','banana')
if 'banana' in fruits:
print('我能买到这种水果')
else:
print('店里没有这种水果卖')


输出:我能买到这种水果

可以使用not in判断不在列表中

#定义一个吃了会导致过敏的水果列表
fruits=('apple','pear','peach','banana')
if 'orange' not in fruits:
print('我能吃这种水果')
else:
print('我对这种水果过敏,我不能吃这种水果')


输出:我能吃这种水果

3、条件判断

条件判断可以使用if语句、if…else语句、if…elif…else语句进行判断

#现在超市搞促销了,苹果0-5斤3元一斤,5-10斤时2.5元一斤,超过10斤时2元/斤,现在要买8斤苹果判断每斤价格
height=8              #购买苹果的重量
if height<=5:
price=3           #购买苹果的价格
elif height<=10:
price=2.5
else:
price=2
print('你购买苹果的价格为:'+str(price)+'元/斤')


输出:你购买苹果的价格为:2.5元/斤
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐