Grape Dragon
Grape Dragon

Reputation: 66

Default Value on Input with Multiple Inputs on Same Line

I want to combine the ability of inputting multiple variables on one line, and having a default value associated if there is no value given. One way to input multiple variables in one line is test1, test2, test3 = input().split() and one way to assign a variable a default value if no variable is given is test1 = input() or 1. For what I need the only variable I need to have a default value will always be the last one, but it would be neat to be able to do it for any variable.

The code I tried is shown below, but it doesn't work.

test1, test2, test3 = input('Enter 2 or 3 variables: ').split() or 1
print(test1)
print(test2)
print(test3)

How I want the code to work when run is like this, when the default variable is 'default'.

# when the user gives 2 variables
>> Enter 2 or 3 variables: variable1 variable2
variable1
variable2
default

# when the user gives 3 variables
>> Enter 2 or 3 variables: variable1 variable2 variable3
variable1
variable2
variable3

Does anybody know how to do this? Using what I've given or not, the inputs need to be all on one line. Another idea I had was to use end = ' ' but I couldn't think of way to actually put it in code.

Upvotes: 1

Views: 867

Answers (1)

Guy
Guy

Reputation: 50899

You can use * with test3 and do some processing on it later

test1, test2, *test3 = input('Enter 2 or 3 variables: ').split()
test3 = test3[0] if test3 else 'default'

test3 will be a list with the third variable as one item, or an empty list if there were only 2 variables.

Upvotes: 1

Related Questions