Python函数if-else分支执行异常:为何不同参数调用结果不同?
问题分析与解决
先看你提供的代码:
def whichIsLarger(x,y): if x > y: print(x, "is greater than ", y) if y > x: print(y, "is greater than ", x) else: print("These numbers are the same!") whichIsLarger(7, 3)
核心问题:else的绑定规则
Python里,else语句会和它上方最近的、未被配对的if语句绑定,而不是和第一个if绑定。你的代码里,else属于第二个if y > x,不是第一个if x > y。
两种调用场景的执行逻辑
调用
whichIsLarger(7,3)时:- 第一个
if x>y(7>3)条件成立,执行print(x, "is greater than ", y),输出第一行。 - 接着执行第二个
if y>x(3>7),条件不成立,所以执行绑定的else语句,输出第二行"These numbers are the same!"。
- 第一个
调用
whichIsLarger(3,7)时:- 第一个
if x>y(3>7)条件不成立,直接跳过。 - 第二个
if y>x(7>3)条件成立,执行对应的print语句,else不会被触发,所以只输出一行。
- 第一个
修正方案
如果要实现“比较两个数,输出较大的那个,相等时提示相同”的逻辑,应该用elif把条件串联起来,让else和第一个if配对:
def whichIsLarger(x,y): if x > y: print(x, "is greater than ", y) elif y > x: print(y, "is greater than ", x) else: print("These numbers are the same!") whichIsLarger(7, 3) # 输出:7 is greater than 3 whichIsLarger(3,7) # 输出:7 is greater than 3 whichIsLarger(5,5) # 输出:These numbers are the same!
内容的提问来源于stack exchange,提问作者Snowbody
相关产品推荐
相关产品推荐

