Python的判断语句

    技术2026-05-02  5

    比较

    在Python中比较语句和其它的一样都是用if来做判断的,只是语法上后面会带上冒号,如if a>b:,相当于if(a>b){}.

    同样你可以判断函数的返回值为True或者False来做判断

    __author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; a = 3 b = 2 c = 2 # True statements if c == b: print('c is equal as b') if c >= b: print('...') if a >= b: print('a is greater than b') if c <= a: print('c is less than a.') if c != a: print('c is not equal as a') # False statements if c == a: print('...')# will show nothing on console if c != b: print('...')# will show nothing on console def inside(): return True if inside(): print ("Inside") else: print("OutSide") 

    Console OutPut:

    Hello c is equal as b ... a is greater than b c is less than a. c is not equal as a Inside  

    多重比较:

    当然你可能会用到 且或这些操作,在Python中是使用and/or 来做到的,看代码吧,从代码中学习语言才是王道:

    __author__="Alex" __date__ ="$2011-2-17 10:39:27$" if __name__ == "__main__": print "Hello"; if 4 > 3 and 6 > 3: print('You are right , 4 is greater than 3 and 6 is greater than 3 too') # will print, True and True becomes True if 4 > 3 and 2 > 3: print('...') # will not print, True and False becomes False if 4 > 3 and not 2 > 3: print('You are right , 4 is greater than 3 and 2 is less than 3 ') # will print, True and not False becomes True if 4 > 3 or 6 > 3: print('You are right...,When 4 is grater than 3 is ture, the condition is ture') # will print, True or True becomes True if (4 > 3 and 6 > 3) and not ( 3 > 5 or 3 > 7): print("(True and True) and not ( False or False ) becomes True and not False")#Complex Multiple Conditions

    Console Output:

    Hello You are right , 4 is greater than 3 and 6 is greater than 3 too You are right , 4 is greater than 3 and 2 is less than 3 You are right...,When 4 is grater than 3 is ture, the condition is ture (True and True) and not ( False or False ) becomes True and not False

    最新回复(0)