Python basic grammar - branch statement presentation

1. Single branch statement

  1. format:

    if a condition: performing one or more lines of code specific

    If the condition is satisfied, if the following block of code is executed; not established is not performed

  2. Case:

    a = 10  # int if a > 5:     print('a > 5')

2. The two branch statement

  1. Formats:

    if a condition: performing one or more lines of code specific elif condition: performing one or more lines of code specific

    If the if condition is true, if the following code is executed

    If elif condition is satisfied, elif following code is executed

    If if elif conditions are true, the first to meet the conditions of the execution of the branch

    If if elif conditions are not satisfied, the two branches are not executed

  2. Case:

    name = 'apple' if name == 'apple': print ( 'I am the apple!') elif name == 'bananas': print ( 'I'm a banana!')
  3. Format II:

    if a condition: performing one or more lines of code specific else: performing one or more lines of code specific

    If the if condition is true, if the following code is executed

    If the if condition is not satisfied, else the following code is executed

    if and else where a code that must be executed

  4. Case:

    name = 'apple' if name == 'apple': print ( 'I am the apple!') else: print ( 'My other fruit!')

3. Multi-branch statement

  1. Formats:

    if a condition: performing one or more lines of code specific elif condition: performing one or more lines of code specific elif three conditions: performing one or more lines of code specific elif four conditions: performing one or more lines of code specific

    If the if condition is true, if the following code is executed

    If elif condition is satisfied, elif following code is executed

    If if elif conditions are true, the first to meet the conditions of the execution of the branch

  2. Case:

    day = input('请输入1-7的数字:')  if day == '1':     print('今天是星期一') elif day == '2':     print('今天是星期二') elif day == '3':     print('今天是星期三') elif day == '4':     print('今天是星期四') elif day == '5':     print('今天是星期五') elif day == '6':     print('今天是星期六') elif day == '7':     print('今天是星期日')
  3. 格式二:

    if 条件一:     执行一行或多行特定代码 elif 条件二:     执行一行或多行特定代码 elif 条件三:     执行一行或多行特定代码 elif 条件四:     执行一行或多行特定代码 else:     执行一行或多行特定代码

    如果 if 条件成立, 则执行 if 下面的代码

    如果 elif 条件成立, 则执行 elif 下面的代码

    如果 if elif 都不满足条件, 则执行 else 下面的代码

  4. 案例:

    f day == '1':     print('今天是星期一') elif day == '2':     print('今天是星期二') elif day == '3':     print('今天是星期三') elif day == '4':     print('今天是星期四') elif day == '5':     print('今天是星期五') elif day == '6':     print('今天是星期六') elif day == '7':     print('今天是星期日') else:     print('无法确定星期几')

注意点:

  1. if代码块必须以if开头, 但不一定以else结尾, else可有可无, 主要是看你代码里需不需要

  2. 如果有else, 只能存在一个, 所以想增加分支一般是通过增加elif语句来增加


Guess you like

Origin blog.51cto.com/14163835/2422668