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循环

  • 相关阅读:
    汇编随笔(第一章 基础知识)
    排序集锦(rough)
    如何让编写的Java代码规范整洁
    二分法查询数据java实现
    归并排序的学习与java实现
    小白的软件测试之路
    PyInstaller打包python脚本
    数据库SQL优化总结
    JQuery选择器
    软件测试面试题
  • 原文地址:https://www.cnblogs.com/qq931399960/p/11101106.html
Copyright © 2011-2022 走看看