How to write a function that takes 2 integers as a parameter and returns the largest of them?

Asked

Viewed 418 times

-4

Write the maximum function that takes 2 integers as parameter and returns the largest of them.

example:

>>> maximo(3, 4)
4
>>> maximo(0, -1)
0
  • 2

    Important you [Dit] your question and explain objectively and punctually the difficulty found, accompanied by a [mcve] of the problem and attempt to solve. To better enjoy the site, understand and avoid closures and negativations worth understanding What is the Stack Overflow and read the Stack Overflow Survival Guide (summarized) in Portuguese. Posting of mere statements does not meet the objectives of the site.

3 answers

4

If you cannot use builtin max that returns the largest item in an iterable or larger than two or more arguments.:

>>> max(3, 4) 
4

Compare the arguments to decide which one is bigger and return it.

def maior1(n1, n2):
    if n1 > n2:
        return n1
    return n2

def maior2(n1, n2):
    return n1 if n1 > n2 else n2
   
maior3 = lambda n1, n2: n1 if n1 > n2 else n2 

print(maior1(4, 8))        #8

print(maior2(32, 2))       #32

print(maior3(687, 8233))   #8233

The three functions maior1(), maior2() and maior3() are equivalent.

-4

def maximo(n1,n2): 
    if n1 > n2:
        print(n1)
    elif n2 > n1:
        print(n2)
    else:
        print(f'{n1} é igual a {n2}')
maximo(0,1)
  • 2

    Note the detail that your function is not returning (read returning) the value as it is prompted, just displaying it.

  • 2

    Another detail: what if n1 is equal to n2?

  • so I added an if and an Elif, I could have added an if and an Else, but if they were equal the largest would be the N2.

-7

Hello! Try that code here:

def mostra_maior(num1, num2):
    if num1 > num2:
        print(num1)
    else:
        print(num2)

mostra_maior(4,8)
>>> 8
  • 4

    And if you do mostra_maior(8, 4), what the exit will be?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.