简体   繁体   中英

Smallest number in an array python

Trying to find the smallest number in an array that the user inputs. Here's what I have:

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()

The result I'm looking for is to be:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is 3

Instead, this is what I am getting:

Give me an array of numbers: [11, 5, 3, 51]
The smallest number is:  5
The smallest number is:  3

Can anyone help me figure out where I am messing up? Thanks in advance.

您可以只使用min()

print("The smallest number is: ", min(numbers))

You have to print the output only once after the loop finishes.

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()

Or use min() as Christian suggested.

Lets assume an array as arr

Method 1: First sorting an array in ascending order & then printing the element of 0 index

arr = [2,5,1,3,0]
arr.sort()
print(arr[0])

Method 2: Using For loop until we get the smallest number then min

arr = [2,5,1,3,0]
min = arr[0]
for i in range (len(arr)):
    if arr[i] < min:
        min = arr[i]
print(min)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM