Write a function that returns the larger of two numbers passed as arguments

Asked

Viewed 732 times

1

I wanted to do this function by grabbing the keyboard input but I’m not getting.

def bigger(a, b):
  a = input('informe um valor: ')
  b = input('Informe outro valor: ')
  if a > b:
     print('O valor a é maior',a)
  else:
     print('O valor b é maior',b)
bigger()

3 answers

1


See the example below:

def bigger():
    a = int(input('informe um valor: '))
    b = int(input('Informe outro valor: '))
    if a > b:
        print('O valor a é maior',a)
    else:
        print('O valor b é maior',b)

bigger()

Note that I have removed the parameters passed, since you will insert them by input within the function.

Note also that I am forcing the data type to int, the same can be done to float.

  • Thank you very much, it helped a lot

0

You are not passing the requested parameters in the function call, and even if you did that you would be comparing text because the input returns a string.

What you should do is read the inputs in the main scope, convert them to integers and pass the inputs to the function.

def bigger(a, b):
  if a > b:
     print('O valor a é maior', a)
  else:
     print('O valor b é maior', b)

a = int(input('informe um valor: '))
b = int(input('Informe outro valor: '))

bigger(a, b)
  • Thanks for the observation and the response, served as a great help.

0

For the purpose of good practice, I will add this answer.

The ideal would be to receive the input, process it and print the result in different functions or places. But since your code is small, no other function is required.

def bigger(a, b):
  if a > b:
     return 'O valor a é maior: %s' % a
  else:
     return 'O valor b é maior: %s' % b

a = float(input('informe um valor: '))
b = float(input('Informe outro valor: '))

print( bigger(a, b) )

Browser other questions tagged

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