在python中实现默认参数功能的用户输入 [英] Achieve the user input for default parameter functionality in python

查看:419
本文介绍了在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)

这篇关于在python中实现默认参数功能的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆