Home > front end >  returning two integers using functions in python
returning two integers using functions in python

Time:11-11

Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem:

  1. Write a function called main that prompts/asks the user to enter two integer values.

  2. Write a value returning function named max that accepts two integer values as arguments and returns the value that is the greater of the two. For example, if 30 and 25 are passed as arguments to the function, the function should return 30.

  3. Call the max function in the main function

  4. The main function should display the value that is the greater of the two.

This is my code, unsure of where I went wrong

def main():
    num1 = int(input('Enter the first number'))
    num2 = int(input('Enter the second number'))
    return num1, num2
    max(n1, n2)
    print(max)



def max(n1, n2):
    return max
    
main()

CodePudding user response:

When you call a the max function you need to read the returned value. What you're printing at the end of main is the max function itself. The issue would be clearer if you renamed the max function "getMax".

A second issue is that no code is executed after return in a function. So the main function stops on the fourth line when it returns num1 and num2.

CodePudding user response:

You've got a lot of it there. Here's how to pull it all together:

def get_max(n1, n2):
    return n1 if n1 > n2 else n2

def main():
    num1 = int(input('Enter the first number> '))
    num2 = int(input('Enter the second number> '))
    print(f"The maximum of {num1} and {num2} is {get_max(num1, num2)}")

main()

Result:

Enter the first number> 345
Enter the second number> 333
The maximum of 345 and 333 is 345

I know the instructions say to create a function named max, but that's the name of a very commonly used function in the standard Python library. It's best that you avoid redefining built in functions by reusing their names.

CodePudding user response:

Here's what you want:

def main():
    num1 = int(input('Enter the first number: '))
    num2 = int(input('Enter the second number: '))
    result = max(num1, num2)
    print(result)

def max(n1, n2):
    if n1 > n2:
        return n1
    else:
        return n2

main()

If you want to use the built-in max() function under the function you created, rename your function to something different to avoid a recursion error.

  • Related