Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an input optional in Python [duplicate]

I am trying to get two variables from one input like this:

x, y = input().split()
print(x, y)

But I want to make the y variable optional, so if the user only inputs x it would only print that value. I get a ValueError if only inserted the x argument.

Anyone knows how to do this?

like image 604
Jackpy Avatar asked Apr 04 '17 13:04

Jackpy


1 Answers

You could use something different from split to 'fake' optional input. Using str.partition you could just catch the first and last element of the resulting tuple:

x, _, y = input().partition(' ')

and then print accordingly:

print(x, y if y else '')

x contains the first value of the input string (after it is splitted on ' ' while y contains the rest.

like image 89
Dimitris Fasarakis Hilliard Avatar answered Sep 19 '22 11:09

Dimitris Fasarakis Hilliard