我的代码有问题,特别是 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
我尝试打印循环的每一步,但我似乎找不到错误
我在 python 中尝试了以下方法并且它有效。
输出:当前列表 > [23, 34, 68, 3, 566, 2, 1]
最小的数字 > 1
最大数量 > 566
检查您的代码后,我发现了导致您的代码在“奇怪”情况下中断的错误。这是您输入数字的 while 循环;如果仔细查看输入函数的文档,您可以看到返回的值被转换为字符串,这意味着以下所有算术运算在某种程度上似乎都可以,但实际上,这些运算没有道理。我修复了以下代码片段中存在问题的部分: