What is -c in Python

Whether you’re a seasoned coder or just dipping your toes into Python, you’ve likely encountered the mysterious -c flag. This seemingly simple two-letter addition unlocks a powerful way to interact with Python directly from the command line. But what exactly does -c do, and how can you harness its potential?

In essence, -c stands for “command mode.” It tells the Python interpreter to treat the following string as a single Python statement, executing it immediately without needing a separate script file. This opens up a plethora of possibilities:

  • Quick testing and experimentation: Need to try out a snippet of code or verify syntax? Throw it after -c and hit enter. No file creation or execution overhead is needed!
  • Interactive calculations: Perform on-the-fly mathematical operations or string manipulations without even launching the interpreter.
  • Simple scripting: Craft short, self-contained scripts directly in the command line for quick tasks.

Here are some examples to illustrate the power of -c:

python -c "print('Hello, world!')"
python -c "print(5 * 5)"
python -c "text = 'apple'; reversed_text = text[::-1]; print(reversed_text)"

Remember: While -c is fantastic for quick checks and small scripts, it’s not ideal for complex projects or code organization. For those, creating proper Python files and using modules is the recommended approach.

Bonus tip: Combine -c with pipes and redirection to create even more powerful command-line workflows. For example, you can use -c to filter data from another program’s output.

So, next time you’re at the command line with Python, don’t underestimate the power of -c. It’s a versatile tool that can boost your productivity and help you experiment with Python in new and exciting ways.

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *