-2

I need a simple one-liner in Python: ask user for choice and then print a message depending on what user chose. Here's my attempt:

python3 -c "ans=input('Y/N?'); if ans == 'Y': print('YES') else: print('NO');"

And errors of course:

  File "<string>", line 1
    ans=input('Y/N?'); if ans == 'Y': print('YES') else: print('NO');
                       ^^
SyntaxError: invalid syntax

Is it possible to do this in one-liner? It must be one-liner, I can't use a script here. Thanks.

mazix
  • 2,540
  • 8
  • 39
  • 56

3 Answers3

2

Solution of your question

python3 -c "ans=input('Y/N?'); print('YES') if ans == 'Y'  else print('NO');"

If you want to add more options you can do like this

python3 -c "options={'Y': 'Yes', 'N': 'No', 'O': 'Other'}; ans=input('Y/N/O?'); print(options.get(ans, 'Undefined'))"

The options defined here is a dictionary mapping user input to display values

Anurag Regmi
  • 629
  • 5
  • 12
1

python3 -c "ans=input('Y/N?'); print('YES') if ans == 'Y' else print('NO')"

0

You can use a ternary expression:

python3 -c "ans=input('Y/N?'); print('YES' if ans == 'Y' else 'NO')"

quamrana
  • 37,849
  • 12
  • 53
  • 71