【问题标题】:Why is a line in my if statement running every time? (python)为什么我的 if 语句中的一行每次都运行? (Python)
【发布时间】:2021-07-19 10:13:07
【问题描述】:

我正在做一个项目,用户输入一个数字和一个列表,列表中最接近数字的任何项目都会被打印出来。我遇到了一个问题,我的 while 循环中的 if() 语句中的行每次都在运行吗?我觉得这与 python 3 中的 if() 语句缩进有关,但我不确定。有人知道为什么会这样吗?

import math
MatchingI = math.inf

while i < len(compareList):
    if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
        MatchingI = int(compareList[i])
    i += 1

【问题讨论】:

    标签: python python-3.x if-statement while-loop


    【解决方案1】:

    我认为您需要将abs(int(mainNum) - int(compareList[i])) 分配给MatchingI,而不是将int(compareList[i]) 分配给MatchingI

    import math
    MatchingI = math.inf
    
    while i < len(compareList):
        if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
            MatchingI = abs(int(mainNum) - int(compareList[i]))
            answer = compareList[i]
        i += 1
    
    print(answer)
    

    这不是你要找的吗?

    【讨论】:

    • @Aaron 我认为您需要两个变量,一个用于差异,另一个用于诸如更大或更小之类的变量。
    • 更有可能(根据命名约定)他们想要MatchingI = i 并且比较为&lt; abs(int(mainNum) - int(compareList[MatchingI]))
    • @Naetmul 我没有看到它出现故障的代码部分,也没有看到代码部分,对不起._.
    • @MarkRansom 是,MatchingI = 0 用于初始化
    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 2021-04-02
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多