Python with -c flag, input from user and if/else inside – shows syntax error

huangapple go评论60阅读模式
英文:

Python with -c flag, input from user and if/else inside - shows syntax error

问题

ans = input('Y/N?'); print('YES' if ans == 'Y' else 'NO')
英文:

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.

答案1

得分: 2

你的问题的解决方案如下:

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

如果你想添加更多选项,可以像这样操作:

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

这里定义的options是一个将用户输入映射到显示值的字典。

英文:

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

答案2

得分: 1

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

英文:

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

答案3

得分: 0

你可以使用三元表达式:

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

英文:

You can use a ternary expression:

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

huangapple
  • 本文由 发表于 2023年2月8日 15:57:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定