尝试查找用户输入的数组中的最小数字。这就是我所拥有的:
def main():
numbers = eval(input("Give me an array of numbers: "))
smallest = numbers[0]
for i in range(0,len(numbers),1):
if (numbers[i] < smallest):
smallest = numbers[i]
print("The smallest number is: ", smallest)
main()
我要找的结果是:
Give me an array of numbers: [11, 5, 3, 51]
The smallest number is 3
相反,这就是我所得到的:
Give me an array of numbers: [11, 5, 3, 51]
The smallest number is: 5
The smallest number is: 3
任何人都可以帮我弄明白我搞砸了吗?提前谢谢。
答案 0 :(得分:4)
您可以使用min()
:
print("The smallest number is: ", min(numbers))
答案 1 :(得分:3)
循环结束后,您只需打印输出一次。
def main():
numbers = eval(input("Give me an array of numbers: "))
smallest = numbers[0]
for i in range(0,len(numbers),1):
if (numbers[i] < smallest):
smallest = numbers[i]
print("The smallest number is: ", smallest)
main()
或者像基督徒建议的那样使用min()
。