在python中实现默认参数功能的用户输入
此处是 C ++
的代码,当未明确提供参数时,我将其默认写入用户输入。
过去一周我一直在学习 Python-3.7
,并试图实现类似的功能。
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.
这是我尝试的代码:
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
此代码有效,但并不完全符合预期。您会看到,当我将参数传递给 foo()
时,它将打印该参数,而当我不传递任何参数时,它将打印用户输入。问题是,即使传递了参数(例如 foo(2)
),它也会要求用户输入,然后忽略用户输入。如何更改它以使其按预期方式工作(因为在传递参数时,它不应要求用户输入)
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)
int(input())
在定义函数时执行 。您应该做的是使用 None
这样的默认值,然后根据需要执行 number = int(input())
:
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)