我正尝试从一个输入中在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
是可选的,并且有一个默认值,但我真的很难实现。
我正尝试从一个输入中在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
是可选的,并且有一个默认值,但我真的很难实现。
# 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
你所能做的最好就是:
answers = input("...").split()
if len(answers) < 4:
answers.append( default_value_for_4 )
如果你真的非常需要将它们称为a、b、c、d,那么只需这样做:
a, b, c, d = answers
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
。a, b, c, d, *_ = (input("...") + " <default value>").split()
d
分配给<default value>
。d
分配给第四个值,并且变量_
的值将是<default value>
(这是Python约定以丢弃值)。