我的循环在某个索引后停止比较

问题描述 投票:0回答:2

我的代码有问题,特别是 for 循环,我在循环中搜索列表中的最小和最大数字。它在某个时刻停止将 a[i] 与当前最小或最大数字进行比较。 我尝试输入 23,34,68,3,566,2,1

 largest = None
    smallest = None
    a = []
    while True:
        num = input("Enter a number: ")
        if num == "done":
            break
        try:
            FailureCond = int(num)
        except ValueError:
            print("that's not a number")
            continue
        a.append(num)
        continue

    for i in range(len(a)):

        if smallest is None:
            smallest = a[i]
            largest = a[i]

        if a[i] < smallest:
            smallest = a[i]

        if a[i] > largest:
            largest = a[i]


    print("current list >",a)
    print("the smallest number is >",smallest)
    print("largest number is >",largest)

输出是

current list > ['23', '34', '68', '3', '566', '2', '1']
the smallest number is > 1
largest number is > 68

我尝试打印循环的每一步,但我似乎找不到错误

arrays list loops
2个回答
0
投票

我在 python 中尝试了以下方法,它有效。


largest = None
smallest = None
a = []

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        num = int(num)  # Convert num to an integer
    except ValueError:
        print("that's not a number")
        continue
    a.append(num)

for num in a:
    if smallest is None:
        smallest = num
        largest = num
    if num < smallest:
        smallest = num
    if num > largest:
        largest = num

print("current list >", a)
print("the smallest number is >", smallest)
print("largest number is >", largest)

输出: 当前列表 > [23, 34, 68, 3, 566, 2, 1]

最小的数字> 1

最大数量> 566


0
投票

检查您的代码后,我发现了导致您的代码在“奇怪”情况下中断的错误。这是你输入数字的 while 循环;如果您仔细查看输入函数的docs,您可以看到返回的值被转换为字符串,这意味着以下所有算术运算在某种程度上似乎都可以,但实际上,这些操作没有意义。我修复了以下代码片段中存在问题的部分:

while True:
    num = input("Enter a number: ")
    if num == "done":
        break
    try:
        FailureCond = int(num)
    except ValueError:
        print("that's not a number")
        continue
    a.append(int(num)) # This line was fixed
    continue
© www.soinside.com 2019 - 2024. All rights reserved.