How to use if...else statement at the command line in Python?



There are multiple ways in which you can use if else construct in the command line in python. For example, bash supports multiline statements, which you can use like:

$ python -c '
> a = True
> if a:
> print("a is true")
> '

This will give the output:

a is true

If you prefer to have the python statement in a single line, you can use the \n newline between the commands. For example,

$ python -c $'a = True\nif a: print("a is true");'

This will give the output:

a is true

Advertisements