英文:
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')"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论