【问题标题】:`else` branch only pair to its nearest 'if'`else` 分支只与它最近的 'if' 配对
【发布时间】:2018-09-12 21:53:14
【问题描述】:

假设以下最小代码:

    x = input("Numeral:  ")
    y = input("Numeral:  ")
    if x < y:
        print(f'{x} is less than {y}.')
    if x > y:
        print(f'{x} is greater than {y}.')
    else:
        print(f'{x} is equal to {y}.')

我喂它然后过来

    $ python3 draft.py
    Numeral:  1
    Numeral:  0
    1 is greater than 0.

运行正常,然后将顺序改为输入:

    $ python3 draft.py
    Numeral:  0
    Numeral:  1
    0 is less than 1.
    0 is equal to 1.

else 分支已执行。

else 分支是否只与最近的“if”配对?
其背后的机制是什么?

【问题讨论】:

标签: python


【解决方案1】:

当然可以——最接近的if 具有匹配的缩进,这就是Python 的编译方式。在您的示例中没有意义:

if x < y:
    print(f'{x} is less than {y}.')
if x > y:
    print(f'{x} is greater than {y}.')
else:
    print(f'{x} is equal to {y}.')

从读者的角度来看,else 引用 x&lt;y。在任何语言中都是一样的(带大括号)。最接近您的意思,但对您的示例没有意义:

if something:
    print("something")
    if otherThing:
        print("that")
else: print("otherwise!")

现在很明显else 属于第一个if。这根本不是 Python 特有的。如果您想要三重检查:

if x > y:
     ...
elif x < y:
     ...
else:
     ...

if (else if) else 构造 - 这是所有语言处理此问题的方式,而不仅仅是 Python。这与以下内容相同:

if x > y:
     ...
else:
    if x < y:
        ...
    else:
        ...

这明确了每个else 所属的位置。

【讨论】:

    【解决方案2】:

    是的,else 仅指最后一个(如果写入)。 您可能想使用elif 而不是第二个if,如果满足第一个if 的条件,它将中断循环。

        x = input("Numeral:  ")
        y = input("Numeral:  ")
        if x < y:
            print(f'{x} is less than {y}.')
        elif x > y:
            print(f'{x} is greater than {y}.')
        else:
            print(f'{x} is equal to {y}.')
    

    【讨论】:

      【解决方案3】:

      python 的语法省略了一些逻辑细节,如果用 shell 代码表示的话

          if (( x < y)); then
              echo "$y is less than $x"
          fi #indicate to terminate the first if
          if (( x > y)); then
              echo "$x is greater than $y."
          else
              echo "$x is equal to $y."
          fi #mark the end of second if
      

      很明显链if, if, if是多任务,而if, elif, elif, else是单任务。

      【讨论】:

        【解决方案4】:

        编辑:过错,这是elif 而不是else if在python中。

        第二个if 应该是elif

        基本上:

        if -> if this is true : do that,
        elif -> else if this second expression is true: do that,
        else -> if everything is false : do that,
        

        【讨论】:

          猜你喜欢
          • 2011-06-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-20
          • 1970-01-01
          • 2018-06-17
          • 1970-01-01
          • 2021-05-25
          相关资源
          最近更新 更多