Make optional Python login

I am trying to get two variables from one input as follows:

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

But I want the variable to ybe optional, so if the user enters only x, he will print only that value. I get a ValueErrorif I just inserted the argument x.

Does anyone know how to do this?

+6
source share
6 answers

Since this is Python 3, here are two lines using extended iterative unpacking.

x, *y = input().split()
y = y[0] if y else ''
+2
source

- split "" . str.partition, :

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

print :

print(x, y if y else '')

x ( ' ', y .

+4

, list. 2, , , .

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

print(x,y)
+1
y     = None
x     = input()

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

print(x, y)
0

:

x, y = (list(input().split()) + [None]*2)[:2]
print(x, y if y else '')
0

:

x, y, *z = input().split() + ['']
print(x, y)
0

Source: https://habr.com/ru/post/1016295/


All Articles