Reputation: 21
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.
Upvotes: 1
Views: 11076
Reputation: 1
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)
Upvotes: 0
Reputation: 1500
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.
Upvotes: 3
Reputation: 34146
You can just use min()
:
print("The smallest number is: ", min(numbers))
Upvotes: 6