808Blues
808Blues

Reputation: 83

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

I'm trying to get specifications three necessary inputs and a fourth optional one from one input in 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()

I want d to be optional with a set default value but I'm really struggling with it.

Upvotes: 3

Views: 729

Answers (4)

bigbounty
bigbounty

Reputation: 17408

You can use the following code

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()

If there are multiple inputs, all will get saved in c which you can further process and assign it to variable d

Upvotes: 0

Selcuk
Selcuk

Reputation: 59315

You can use this:

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

This will assign d to <default value> if there are only 3 inputs.

If there are 4 inputs then d will be assigned to the fourth value, and the value of the variable _ will be <default value> (which is a Python convention to discard a value).

Upvotes: 0

Kate Melnykova
Kate Melnykova

Reputation: 1873

# 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

Upvotes: 1

Tim Roberts
Tim Roberts

Reputation: 54733

The best you can do is:

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

If you really really feel the need to have them called a, b, c, d, then just do:

a, b, c, d = answers

Upvotes: 0

Related Questions