baboo12345
baboo12345

Reputation: 23

Python: Is it possible to judge input using if statement in one line

I'm using python 3.6. I want to input a string or something and judge it by if statement in one line. This might be a simple question but I couldn't solve this problem. I know how to do in without one line:

words = input()
if words == 'a':
    print(words)
else:
    print('Not a')

However, I couldn't put it into one line. What I want to do is like this:

print(input() if input() == 'a' else 'Not a')

It doesn't work. The first input and the second input is different. Is it possible to keep the result of first input and check its condition in one line? Thanks!

Upvotes: 2

Views: 863

Answers (2)

user2390182
user2390182

Reputation: 73490

You can use the singleton generator/list trick to avoid calling a function twice, but still reuse its result:

print(next(x if x == 'a' else 'Not a' for x in [input()]))

While you're at it, you can also shorten the ternary x if y else z construct to become even more cryptic :-)

print(next(('Not a', x)[x == 'a'] for x in [input()]))

But fewer lines are not an end in itself. The five lines you have are perfectly valid and readable.

Upvotes: 5

Jonathon McMurray
Jonathon McMurray

Reputation: 2991

>>> words = input()
'a'
>>> print(words if words=='a' else 'not a')
a
>>> words = input()
'b'
>>> print(words if words=='a' else 'not a')
not a

Upvotes: 0

Related Questions