0

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)

1

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.