-2

Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python. (It is true that Python has the max() function built in, but writing it yourself is nevertheless a good exercise.)

def max(a,b):
    if a > b:
        print (a)
    elif a < b:
        print (b)
    elif (a==b):
        return (a)
    print ("function executed")
    print (max(4,5))

max(1,2)

The output of this function is,

2
function executed
None
5
function executed
None
poke
  • 307,619
  • 61
  • 472
  • 533
user3421311
  • 161
  • 2
  • 9
  • 3
    You have not yet met the specification - your function doesn't return anything. Also, it fails in the case `a == b`. – jonrsharpe Oct 12 '14 at 15:31
  • 3
    And how do you define the *elegant*? – m0nhawk Oct 12 '14 at 15:31
  • Good point. Thanks. I tried return, but it doesn't print anything to the console. – user3421311 Oct 12 '14 at 15:33
  • Its not supposed to print anything, its just supposed to return the largest of two. – Burhan Khalid Oct 12 '14 at 15:35
  • 2
    @user3421311 You should not edit your question so much that it becomes an entirely different question. Either ask a new question, or request a clarification to the answer in the comments. – parchment Oct 12 '14 at 15:57
  • I reverted the question to its original state. To answer your follow-up question: When `a == b`, then `a > b` is false, so whatever happens in the `else` part is used for both `a < b` **and** `a == b`. – poke Oct 12 '14 at 16:42

1 Answers1

3

You can use a conditional expression, like this

def max(a, b):
    return a if a > b else b

Since the function just returns the biggest value, you might want to print the result yourself, like this

print max(1, 2)

Or if you are using Python 3.x, then print is not a statement, but a function. So, it has to be called like this

print(max(1, 2))
Community
  • 1
  • 1
thefourtheye
  • 206,604
  • 43
  • 412
  • 459