Achieve the user input for default parameter functionality in python

柔情痞子 提交于 2020-06-16 23:43:10

问题


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:


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)


来源:https://stackoverflow.com/questions/61939282/achieve-the-user-input-for-default-parameter-functionality-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!