零基础学python-11.1 if语句
1.通用格式
if condition1: statement1 elif condition2: statement2 else: statement3
解释:如果condition1为真,执行statement1,如果condition1为假,检查condition2,如果为真,执行statement2,如果两个都为假,则执行statement3
2.例子:
>>> if 1 : print(True) True >>> if 2>0: print(True) True
>>> if 2<0:print(False) elif 1<2<3 :print(True) True >>>
3.多路分支
>>> person='killer'
>>> if person=='police':print('hi police')
elif person=='teacher':print('morning sir')
elif person=='killer':print('run away')
run away
>>> >>> person='teacher'
>>> if person=='police':print('hi police')
elif person=='teacher':print('morning sir')
elif person=='killer':print('run away')
morning sir>>> person='police'
>>> if person=='police':print('hi police')
elif person=='teacher':print('morning sir')
elif person=='killer':print('run away')
hi police
>>> 在上面的代码里面,我们演示了if的多路分支,根据不同的条件,来判断需要完成不同的事情
注意:python里面是没有switch...case...这个语法,所有分支都需要写成if...elif...else...
我们在演示另一种多路分支,主要使用在字典里面
>>> choice='a'
>>> print({'a':1,'b':2,'c':3}[choice])
1
>>> 上面的例子如果换成if...elif...else语法就像下面的
>>> choice='a' >>> if choice=='a':print(1) elif choice=='b':print(2) elif choice=='c':print(3) 1 >>>
对比上面两段代码,第一段代码无疑根据优雅
就说到这里,谢谢大家
------------------------------------------------------------------
版权声明:本文为博主原创文章,未经博主允许不得转载。
浙公网安备 33010602011771号