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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With