Python基础入门-IF语句

今天给大家分享一下Python中的IF语句的使用场景以及注意事项。主要内容如下:

  • 1.python中的真假
  • 2.Python操作符
  • 3.if语句实例和嵌套实例
  • 4.if语句中的if嵌套实例
  • 5.and和or的运算关系演示

首先我们看一个IF语句处理的流程图:

《Python基础入门-IF语句》

IF语句运行原理就是:给出条件,决定下一步怎么做?如果条件为真,就执行决策条件代码块的内容,为假就退出。

我们学习之前先看下Python中的真假:在python中,任何非零,非空对象都是真,除真和None以外其他的都是假。

来敲一下笔记:

  • 1.任何非零和非空对象都为真 解释为True
  • 2.数字0、空对象和特殊对象None均为假 解释为False
  • 3.比较和相等测试会应用到数据结构中
  • 4.返回值为True或False

我们来看几个例子细细品味一下:

>>> not 0 True >>> not 1 False >>> not [] True >>> not [1] False >>> not True False >>> not False True

ok,你知道了真假以后,然后我们来简单介绍一下python中的常用的几种运算符.因为条件语句和运算符的结合是经常会用到的。

Python操作符介绍

1.算术运算符  +  -  *   / (取商)  %(取余数)  **
2.赋值运算符     num=100     num = num + 90
3.成员关系运算符  in  not in 
4.比较运算符   >  <  >=  < =   ==  !=  <> 

接下来看一下关于IF语句中的一些常用的实例……

1.if语句基本构成

  if 条件:     if语句块   else:       else语句

if语句用于比较运算(大于>)中

a = 0 if a > 0: print "a is not 0"
else: print 'a is o'

if语句用于比较运算中结合逻辑运算符

a = 50
if a< 100 and a > 10: print "a is not 0"
else: print 'a is false'

and的优先级大于or有括号的运算最优先

a = 50
if (a< 100 and a > 10 or (a >20 and a<100): print "a is true"
else: print 'a is false'

2.if结合比较运算操作符:  ><  ==  >=   <=  ==  !=  <>

a =90 b =100
if a>b: print "a is max"
else: print 'a is min'

IF语句结合不等于实例:

a =90 b =100
if a<>b: print "a is max"
else: print 'a is min'

IF语句结合成员关系运算符:In  (not  in )

name  = 'zhangshan'
if  'zhang'  not in name: print 'zhang is in name'
else: print  'zhang is not in name'

3.if elif嵌套结构

if 条件: if语句块 elif 条件: elif语句块 else: else语句块

用于检查多个条件是否满足:

number1 = int(input("请输入数字1:")) number2 = int(input("请输入数字2:")) if    number1 > number2: print "{} 大于 {}".format(number1,number2) elif  number2 < number2: print  "{} 小于 {}".format(number1,number2) elif  number1 == number2: print '%s 等于 %s'%(number1,number2) else: print 'game is over'

IF嵌套语句2

最外侧if语句作为整个if语句中的决策条件,优先满足后,才可以继续和if子句进行在判断,如果一开始输入的内容不符合决策条件,就直接退出整个if分支语句。

name = input("请输入信息:") if  name.endswith('hello'): if name.startswith('china'): print 'welcome to {}'.format(name) elif name.startswith('japan'): print 'say you {}'.format(name) else: print '输入有误,重新输入'
else: print  '游戏结束---->'

写在最后补充-对Python而言:

 其一, 在不加括号时候, and优先级大于or 其二, x or y 的值只可能是x或y. x为真就是x, x为假就是y 其三, x and y 的值只可能是x或y.  x为真就是y, x为假就是x
看几个实际的例子
>>> 5 and 6 and 7 7 >>> 4 and 5 or 6 and 7 5 >>> True or True and False True >>>
    原文作者:IT测试老兵
    原文地址: https://www.cnblogs.com/fighter007/p/8267615.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞