You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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。

两种调用场景的执行逻辑

  1. 调用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!"。
  2. 调用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:42:43