假设以下最小代码:
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
分支只能将其离与最接近的"如果"?
其背后的机制是什么?
当然是 - 最接近匹配凹痕的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<y
。在任何语言(带牙套(中都是相同的。最接近您的意思,但对于您的示例没有意义:
if something:
print("something")
if otherThing:
print("that")
else: print("otherwise!")
现在很明显else
属于第一个if
。这根本不是Python的特定于Python。如果您需要三次检查:
if x > y:
...
elif x < y:
...
else:
...
if (else if) else
构造 - 这就是所有语言处理此操作的方式,而不仅仅是Python。这与:
if x > y:
...
else:
if x < y:
...
else:
...
清楚每个 else
属于何处。
是的, 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}.')
python的语法省略了一些逻辑细节,如果在shell code中表达
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
是单个任务。
编辑:mea culpa,是python中的 elif
不是 else if
。
第二个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,