python 如何为一行中的多个输入设置默认值

How to set default value for multiple inputs from one line in python

我正在尝试从 Python 中的一个输入中获取规范中的三个必要输入和第四个可选输入。

a, b, c, d = input("Please enter the number of the figure you would like and the x y coordinated in that order and a colour if you choose.").split()

我希望 d 是可选的并设置默认值,但我真的很难做到。

你能做的最好的是:

answers = input("...").split()
if len(answers) < 4:
    answers.append( default_value_for_4 )

如果您真的觉得有必要将它们命名为 a、b、c、d,那么就这样做:

a, b, c, d = answers
# get input
inp = input("Please enter the number of the figure you would like and the x y coordinated in that order and a colour if you choose.").split()
# check how many parameters are passed
if len(input) == 3:
    # value for d is not passed
    a, b, c = inp
    d = default_value
else:
    # value for d is passed
    a, b, c, d = inp

你可以使用这个:

a, b, c, d, *_ = (input("...") + " <default value>").split()

如果只有 3 个输入,这会将 d 分配给 <default value>

如果有 4 个输入,那么 d 将被分配给第四个值,变量 _ 的值将是 <default value>(这是一个 Python 丢弃值的约定)。

您可以使用以下代码

a , b , *c = input("Please enter the number of the figure you would like and the x y coordinated in that order and a colour if you choose.").split()

如果有多个输入,所有输入都将保存在 c 中,您可以进一步处理并将其分配给变量 d