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

There are multiple ways you can use if...else statements at the command line in Python. The command line allows both multiline and single-line approaches for executing conditional logic.

Using Multiline Statements

Bash supports multiline statements, which you can use with Python's -c flag ?

# In terminal/command line:
# python -c '
# a = True
# if a:
#     print("a is true")
# else:
#     print("a is false")
# '

This approach allows you to write Python code exactly as you would in a script file, with proper indentation and structure.

Using Single-Line with Newline Characters

You can compress the if...else statement into a single line using \n newline characters ?

# In terminal/command line:
# python -c $'a = True\nif a:\n    print("a is true")\nelse:\n    print("a is false")'

Using Ternary Operator

For simple conditions, the ternary operator provides the most concise approach ?

# In terminal/command line:
# python -c "a = True; print('a is true' if a else 'a is false')"

Complete Example with User Input

Here's a practical example that takes user input and uses if...else logic ?

import sys

# Simulating command line: python -c "code_here"
number = 15
if number > 10:
    print(f"{number} is greater than 10")
else:
    print(f"{number} is not greater than 10")
15 is greater than 10

Comparison of Methods

Method Readability Best For
Multiline High Complex logic
Single-line with \n Medium Moderate complexity
Ternary operator High Simple conditions

Conclusion

Use multiline approach for complex if...else logic, single-line with \n for moderate complexity, and ternary operators for simple conditions. Choose the method that best fits your command-line scripting needs.

Updated on: 2026-03-24T20:37:07+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements