Reputation: 45
Q: Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python
max()
function!
I Was Working On This Problem And I Almost Finished This But I Am Encountering A Very Silly Problem Of How To Call This Function:
def findingmax(a, b, c):
if (a > b) and (a > c):
print(f"Max Number Is: {a}")
elif (b > a) and (b > c):
print(f"Max Number Is: {b}")
elif (c > a) and (c > b):
print(f"Max Number Is: {c}")
else:
pass
Numbers = input("Enter Three Numbers: ")
print(findingmax(Numbers)
Upvotes: 0
Views: 1499
Reputation: 9
So here you can use this code for simple max finder program.
You have to change the input style like the following so you can take input in multiple variables at a time, .split()
function is used to differentiate the characters by space and split them and input function insert that value accordingly.
The format()
method formats the specified value(s) and insert them inside the string's placeholder ({}
).
def findingmax(a, b, c):
if (a > b) and (a > c):
print("Max Number Is:{}".format(a))
elif (b > a) and (b > c):
print("Max Number Is: {}".format(b))
elif (c > a) and (c > b):
print("`enter code here`Max Number Is: {}".format(c))
else:
pass
a, b,c = input("Enter a 3 value: ").split()
a=int(a)
b=int(b)
c=int(c)
print(findingmax(a,b,c))
Upvotes: 0
Reputation: 2533
Here's a fancy way:
Numbers = map(int, input("Enter Three Numbers: ").split())
print(findingmax(*Numbers))
This lets you enter 3 numbers on one line, splits them, and converts them to a integers. *Numbers
splits them up so you can use them as arguments.
Additionally, your function will not return anything if 2 of the numbers are tied for the maximum, and you also said that you wanted to return the largest one, which is different from printing the largest one. Here's an updated version of findingmax()
which returns the max rather than printing it, and will work correctly in the case of a tie:
def findingmax(a, b, c):
if (a > b) and (a > c):
return a
elif b > c: #if reached this point, b or c must be >= a
return b
else:
return c
Upvotes: 2
Reputation: 4354
Your input is a string so you can do something like this:
n1 = int(input("Enter the first number"))
n2 = int(input("Enter the second number"))
n3 = int(input("Enter the third number"))
print(findingmax(n1, n2 n3))
Upvotes: 2