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

3

我正尝试从一个输入中在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是可选的,并且有一个默认值,但我真的很难实现。

4个回答

1
# 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

0

你所能做的最好就是:

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

如果你真的非常需要将它们称为a、b、c、d,那么只需这样做:

a, b, c, d = answers

0
您可以使用以下代码。
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

0
你可以使用这个:
a, b, c, d, *_ = (input("...") + " <default value>").split()

如果只有3个输入,则将d分配给<default value>
如果有4个输入,则将d分配给第四个值,并且变量_的值将是<default value>(这是Python约定以丢弃值)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接