zoukankan      html  css  js  c++  java
  • Python中循环及判断语句

    循环判断条件是编程语言中一个很重要的部分,python也不例外,循环判断条件一般结合continue,return,break关键字来判断,这些关键字用法与java中基本一致

    一、if判断语句

    判断条件返回的结果为布尔值,在python中,布尔值为True/False,首字母必须大写,否则将出现如下异常

    >>> ls=false
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'false' is not defined
    View Code

    python中,值不为空时,判断条件为True,如

    >>> str='flag'
    >>> if str:
    ...     print("not empty")
    ... else:
    ...     print("empty")
    ... 
    not empty
    >>> str=''
    >>> if str:
    ...     print("not empty")
    ... else:
    ...     print("empty")
    ... 
    empty
    View Code

    单个判断条件

    >>> tup=('dog','cat','water','bj')
    >>> for val in tup:
    ...      if len(val) < 3:
    ...          print("the length of " + val + " is less than 3")
    ...      elif len(val) == 3:
    ...          print("the length of " + val + " is 3")
    ...      else:
    ...          print ("the length of " + val + " is more than 3")
    ... 
    the length of dog is 3
    the length of cat is 3
    the length of water is more than 3
    the length of bj is less than 3

    多个判断条件可以使用and或者or

    >>> name="xiao"
    >>> if name != "" and len(name) > 3:
    ...     print ("long name")
    ... else:
    ...     print ("short name")
    ... 
    long name
    >>> weight=100
    >>> if weight > 150 or weight < 60:
    ...     print ("no normal weight")
    ... else:
    ...     print ("normal weight")
    ... 
    normal weight

     判断某个值是否在列表中存在

    >>> ls=['car','cat','dog']
    >>> if 'car' in ls:
    ...     print("yes, it is car")
    ... else:
    ...     print("no car")
    ... 
    yes, it is car

    while循环

    >>> i=5
    >>> while(i>1):
    ...     i-=1
    ...     print(i)
    ... 
    4
    3
    2
    1

    for循环

  • 相关阅读:
    07_Python语法示例(基础语法,文件操作,异常处理)
    练习js——自动化实现12306火车票查询
    【转】app自动化问题点整理
    TouchAction的花式应用——APP九宫格绘制
    【转】web 自动化文件上传不要太简单
    阶段小测试我的作业
    Mac Chrome浏览器取消自动升级
    Mac下安装selenium及Chromedrive驱动
    【转】Jenkins配置Git push后自动构建
    函数使用练习
  • 原文地址:https://www.cnblogs.com/qq931399960/p/11101106.html
Copyright © 2011-2022 走看看