▶️ Running Python Code¶
There are several ways to run Python code. Understanding them will make your learning journey smoother.
Method 1: Running a Python File¶
This is the most common way to run Python programs.
Steps:¶
- Create a file with a
.pyextension (e.g.,my_program.py) - Write your Python code in the file
- Open terminal/command prompt
- Navigate to the file's directory
- Run:
python my_program.py
Example:¶
Create greet.py:
Run it:
Output:
Method 2: Python Interactive Mode (REPL)¶
REPL = Read-Evaluate-Print-Loop
Great for quick experiments and testing small pieces of code.
How to Start:¶
You'll see:
Try It:¶
>>> 2 + 2
4
>>> print("Hello!")
Hello!
>>> name = "Python"
>>> f"I love {name}"
'I love Python'
>>> exit() # To leave
Method 3: Running Code in Your Editor¶
Most modern editors can run Python directly.
VS Code:¶
- Open your
.pyfile - Click the ▶️ (Play) button in the top-right
- Or press
Ctrl+F5(Windows) /Cmd+F5(Mac)
PyCharm:¶
- Open your
.pyfile - Right-click → "Run 'filename'"
- Or press
Shift+F10
Method 4: Jupyter Notebooks¶
Interactive notebooks that mix code, output, and documentation.
Install:¶
Start:¶
This opens in your browser where you can create .ipynb files.
Great for: - Data science - Learning (see code + results together) - Experimentation
Which Method Should You Use?¶
| Situation | Recommended Method |
|---|---|
| Learning concepts | REPL or Jupyter |
| Writing real programs | Python files + Editor |
| Quick calculations | REPL |
| Sharing code | Python files |
| Data analysis | Jupyter Notebooks |
Common Commands Reference¶
# Run a Python file
python filename.py
# Start interactive mode
python
# Check Python version
python --version
# Install a package
pip install package_name
# List installed packages
pip list
💡 Tips¶
- Always save your file before running it
- Use meaningful file names like
calculator.pynottest1.py - Don't name your files after Python modules (e.g., don't create
random.py) - Read error messages — they usually tell you what's wrong
✅ Next Step¶
Now that you know how to run Python code, learn how to use this repository effectively!