zoukankan      html  css  js  c++  java
  • 零基础学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
    >>> 

    对比上面两段代码,第一段代码无疑根据优雅

    就说到这里,谢谢大家

    ------------------------------------------------------------------

    点击跳转零基础学python-目录



    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    hexo常用命令笔记
    给hexo添加评论系统
    npm 使用代理
    几种网页重定向(自动跳转)的方法
    使用hexo搭建github博客
    在Pythonanywhere上部署Django
    Apache .htaccess语法之RewriteRule
    为Github项目创建文档
    Windows下WordPress搭建博客过程
    Windows下Discuz搭建论坛过程
  • 原文地址:https://www.cnblogs.com/raylee2007/p/4896764.html
Copyright © 2011-2022 走看看