Search code examples
pythonfunctiondefault-arguments

Achieve the user input for default parameter functionality in python


Here is a C++ code I wrote to default to user input when arguments are not provided explicitly. I have been learning Python-3.7 for the past week and am trying to achieve a similar functionality.

This is the code I tried:

def foo(number = int(input())):
    print(number)

foo(2)  #defaults to user input but prints the passed parameter and ignores the input
foo()   #defaults to user input and prints user input

This code works, but not quite as intended. You see, when I pass an argument to foo(), it prints the argument, and when I don't pass any, it prints the user input. The problem is, it asks for user input even when an argument has been passed, like foo(2), and then ignores the user input. How do I change it to work as intended (as in it should not ask for user input when an argument has been passed)


Solution

  • int(input()) is executed when the function is defined. What you should do is use a default like None, then do number = int(input()) if needed:

    def foo(number=None):
        if number is None:
             number = int(input())
        print(number)