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

来源:互联网 发布:德国面包 知乎 编辑:程序博客网 时间:2024/06/05 07:44

我在需要区分不同条件下的不同情况时,需要使用到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.5else:    price=2print('你购买苹果的价格为:'+str(price)+'元/斤')

输出:你购买苹果的价格为:2.5元/斤

原创粉丝点击