I have just started learning python and I am trying to use if/else statement in python -c, but I keep getting Invalid Syntax error. The reason I want to call if/else with python -c is because I want to call some python modules with if/else in my bash script. Is it possible and I would like to stick to python -c and not python -m?
Below is what I have tried so far
python -c "if False: print 'not working';else print 'working'"
File "<string>", line 1
if False: print 'not working';else print 'working'
^
SyntaxError: invalid syntax
python -c "if False: print 'not working';else: print 'working'"
File "<string>", line 1
if False: print 'not working';else: print 'working'
^
SyntaxError: invalid syntax
python -c "if False:; print 'not working';else:; print 'working'"
File "<string>", line 1
if False:; print 'not working';else:; print 'working'
^
SyntaxError: invalid syntax
Any suggestions on how I can fix this issue?
And what if I want to use if|elif|elif|else kind of statement?
Thanks in advance!
Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
Other programming languages like C++ and Java have ternary operators, which are useful to make decision making in a single line. Python does not have a ternary operator. But in python, we can use the if-else in a single line, and it will give the same effect as the ternary operator.
Here's an example:if 51<5: print("False, statement skipped") elif 0<5: print("true, block executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")
In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
For a true general-purpose solution -- python -c
is not limited to single lines.
python -c '
if True:
print "hello"
else:
print "world"
'
Of course, you can format your multi-line string as a single line, if you really want to:
python -c $'if True:\n\tprint "hello"'\nelse:\n\tprint "world"'
...but, also quite obviously, this is a Really Bad Idea.
If you really, really want to wrap Python code in shell, why not use functions? Even better than that, why not use quoted heredocs for your code? (Doing this lets you keep the code itself literal, passing arguments through argv).
python_argv_repr() {
python - "$@" <<'EOF'
import sys
print sys.argv[1:]
EOF
}
Make it simple, use the ternary form:
$ python -c "print 'A' if False else 'B'"
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