Reputation: 3
The explanation is below:
def displaySortedNumbers(num1, num2, num3):
smallest = num1
if num2 < smallest:
smallest = num2
if num3 < smallest:
smallest = num3
return smallest
def main():
num1, num2, num3 = eval(input("Enter three numbers seperated by commas:"))
print("The numbers are,",displaySortedNumbers(num1, num2, num3))
main()
After the three numbers are entered, the smallest number prints out but the rest of the numbers do not follow. I need the numbers to print out from smallest to largest. I'm not sure what I did wrong.
Upvotes: 0
Views: 208
Reputation: 21
Your function is only returning the one smallest number of the provided three, you may consider using a list and sorting it instead if that works for you.
def displaySortedNumbers(num1, num2, num3):
s = ""
for c in sorted([num1, num2, num3]):
s += " " + str(c)
return s
The sorted()
function takes an iterable argument and returns it sorted by a key, however in this case, if you are just sorting it in increasing order, you do not need to input a key.
Upvotes: 2
Reputation: 5690
In your return statement, you only return one of the three numbers, the one you deem the smallest. But your function is expected to return all three numbers sorted. I'm guessing you can't use the built-in sorted()
function and so you need to program the sort manually. You can do a simple bubble sort on 3 numbers by changing your function to be the following:
def displaySortedNumbers(num1, num2, num3):
if num2 < num1:
num1, num2 = num2, num1
if num3 < num2:
num2, num3 = num3, num2
if num2 < num1:
num1, num2 = num2, num1
return num1, num2, num3
This will print all three numbers, properly sorted.
If you CAN use built-in functions, you could simply say:
def displaySortedNumbers(num1, num2, num3):
return sorted((num1, num2, num3))
Upvotes: 0
Reputation: 24
In your return statement there is only ´smallest´, not the other variables.
You can store the values in a list, sort it and then return that list, just like this
def displaySortedNumbers(num1, num2, num3):
list = [num1, num2, num3]
list.sort()
return list
Upvotes: 0
Reputation: 1
Try to rewrite like this:
if smallest > num2:
smallest = num2
elif smallest > num3:
smallest = num3
Upvotes: -1