循环判断条件是编程语言中一个很重要的部分,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
python中,值不为空时,判断条件为True,如
>>> str='flag' >>> if str: ... print("not empty") ... else: ... print("empty") ... not empty >>> str='' >>> if str: ... print("not empty") ... else: ... print("empty") ... empty
单个判断条件
>>> 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循环
略