6

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?

manvi77
  • 536
  • 1
  • 5
  • 15
Jackpy
  • 111
  • 5

6 Answers6

4

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • `x, y = input().partition(' ')[::2]` as in the suggested dupe http://stackoverflow.com/questions/749070/partial-list-unpack-in-python – Chris_Rands Apr 04 '17 at 14:17
  • @Chris_Rands I would personally stick with the throw-away instead of going with a slice, it's not worth it in my view at least. (p.s: Hammered, thanks for pointing it out!) – Dimitris Fasarakis Hilliard Apr 04 '17 at 14:29
2

Since this is Python 3, here's two lines using extended iterable unpacking.

x, *y = input().split()
y = y[0] if y else ''
timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You cannot unpack your variables at once, you have to check size of the returned list object first. If size isn't 2, just fill with default, else proceed unpacking as you did.

toks = input().split()
if len(toks)==2:
    x,y = toks
else:
    x = toks[0]
    y = "default"

print(x,y)
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0
y     = None
x     = input()

if ' ' in x:
    x, y = x.split()

print(x, y)
MarianD
  • 13,096
  • 12
  • 42
  • 54
0

You can go:

x, y = (list(input().split()) + [None]*2)[:2]
print(x, y if y else '')
zipa
  • 27,316
  • 6
  • 40
  • 58
0

A one-liner way of doing this:

x, y, *z = input().split() + ['']
print(x, y)
Neil
  • 14,063
  • 3
  • 30
  • 51