How to Execute Specific Lines of Code in Python
Shift+Enter lets you execute a selected line or group of lines in Visual Studio Code instead of running the entire Python file. In Microsoft’s VS Code Python extension, you can send a selection to a Python REPL, test one statement interactively, or refactor a script so the part you need is a named function. Python cannot safely “jump” into the middle of an arbitrary script line-by-line because the code often depends on imports, variables, and setup that ran earlier.
What Executing Specific Lines in Python Means
A Python file normally runs from top to bottom. Before Python can execute a statement, it must be able to parse the surrounding code and have the names that statement depends on available.
For example, this line cannot run by itself if subtotal has not been created:
tax = subtotal * 0.07
Likewise, a single indented line inside a function, loop, if statement, or try block is usually not a complete runnable unit. Python uses indented lines in compound statements such as loops:
for item in items:
print(item)
Executing selected code is therefore not the same as starting a script at line 50. You are sending a valid fragment to a Python interpreter that already has, or is also given, the imports, variables, and definitions it needs.
The most dependable choices are:
- Send a self-contained selection to a REPL while experimenting.
- Type an individual statement in the Python REPL.
- Put repeatable sections into functions and call the function you need.
- Split notebook work into small cells.
- Run the complete file when you need to verify the real program flow.
How to Execute Specific Lines in VS Code
Use this method when you are editing a .py file in VS Code and want quick feedback without running all of it.
Choose the execution method that matches what you are testing.
| What You Need to Run | Best Choice | Result |
|---|---|---|
| A selected expression, assignment, or block | Select it and use Shift+Enter | Sends the selection to the Python REPL |
| The smallest valid chunk around the cursor | Put the cursor in the code and use Smart Send | Runs a complete runnable unit rather than necessarily one physical line |
| One physical cursor line | Disable Smart Send in VS Code settings | Sends only the line containing the cursor |
| A complete saved program | Run the file in the terminal | Executes top-level code from the beginning |
Step 1: Start a Python REPL for the Selected Interpreter
- Install Python and the VS Code Python extension if they are not already available.
- In VS Code, choose the Python interpreter you want the file to use.
- Open the Command Palette and run
Python: Start Terminal REPL.
VS Code opens a terminal using the currently selected interpreter. The >>> prompt means the interpreter is ready to receive Python code.
If you prefer VS Code’s Native REPL instead of the terminal REPL, add this setting to your existing settings.json file:
{
"python.REPL.sendToNativeREPL": true
}
With that setting enabled, use the Run Selection/Line in Python REPL command to send code to the Native REPL.
Step 2: Select a Complete, Self-Contained Fragment
- Highlight the line or lines you want to test.
- Include the imports, variable assignments, and helper functions that fragment requires.
- Include the complete body of any
if,for,while,try,with, class, or function statement.
For example, select all four lines here if you want the snippet to work in a fresh REPL:
subtotal = 19.95
tax_rate = 0.07
total = subtotal + subtotal * tax_rate
print(total)
Selecting only the last line works only if the first three assignments have already run in the same interpreter session.
Be especially careful with code that changes files, databases, queues, or external services. Running a selection twice can create duplicate records, overwrite output, or send the same request again.
Step 3: Send the Selection or Cursor Line to Python
- After selecting one or more lines, press Shift+Enter.
- Alternatively, right-click the selection and choose
Run Selection/Line in Python Terminal. - Read the output and any traceback in the REPL panel.
When there is no selection, VS Code’s default Smart Send behavior examines the cursor location and sends the smallest runnable chunk to the REPL. For a cursor inside a loop or function, that can mean more than the one visible physical line, which prevents invalid partial-block execution.
If you specifically want the cursor line sent without Smart Send choosing a larger block, add this property to VS Code’s settings.json file:
{
"python.REPL.enableREPLSmartSend": false
}
Smart Send requires supported, syntactically valid Python code. It will not work with unsupported versions such as Python 2 or with code that Python cannot parse.
Step 4: Verify the Result in a Clean State
- Check the printed result, returned value, or error message.
- If the selection depends on earlier work, identify every required import, variable, and function.
- Restart the REPL or open a new terminal, then run only the required setup and selection again.
- If the fragment succeeds only after unrelated earlier commands, move its dependencies into a function, setup block, or test fixture.
A NameError usually means the selected code refers to a variable or function that has not been defined in the current interpreter. A SyntaxError often means you selected only part of an indented block or unfinished expression.
Run Individual Statements in the Python REPL
The standard Python REPL is the simplest option when you want to run one statement outside an editor.
On Windows, start it with:
python
On macOS and Linux, the common command is:
python3
Your operating system’s Python installation determines which invocation is available. Once the >>> prompt appears, enter a valid statement:
total = 6 * 7
Then inspect it:
print(total)
The REPL evaluates each complete statement immediately and retains values for the rest of that session.
For a compound statement such as a loop or function, enter the whole block and then submit a blank line to tell the REPL the block is complete:
for number in range(3):
print(number)
The REPL is useful for calculations, inspecting objects, testing a function call, and checking how a library behaves. It is less suitable for a repeatable workflow because session state can hide missing setup.
Run Parts of a Script Reliably
If you often need to skip tasks, rerun a pipeline stage, or call a script “from the middle,” restructure the script around functions. Python has no general-purpose goto statement for jumping to a chosen source line, and forcing arbitrary line execution makes dependencies difficult to understand.
def normalize(text):
return text.strip().lower()
def main():
raw_value = " Example Value "
print(normalize(raw_value))
if __name__ == "__main__":
main()
Save that file as pipeline.py. Running the file executes main(), but importing it makes normalize() available without automatically starting the whole program:
from pipeline import normalize
result = normalize(" Example Value ")
print(result)
The if __name__ == "__main__": guard is what prevents main() from running during the import.
def main(write_output=True):
records = load_records()
cleaned_records = clean_records(records)
if write_output:
write_records(cleaned_records)
You can then call the program logic without the final output stage:
main(write_output=False)
This approach is safer than jumping past lines because the code still runs in a deliberate order. It also makes the behavior easier to test and reuse.
Avoid using exec() to run arbitrary text just to target parts of a source file. It does not solve missing dependencies, makes debugging harder, and is unsafe when the string could contain untrusted input.
Run the Whole File When Program Order Matters
Use a selection for a small experiment, but run the complete file when you need to validate the program’s actual startup order and side effects.
For a saved script named hello.py, run the full file from its directory on Windows with:
python hello.py
On macOS or Linux, use:
python3 hello.py
In VS Code, select the green Run Python File in Terminal button in the editor, or use Ctrl+F5 to run the active file. This is the right choice when imports, command-line configuration, file paths, environment variables, or top-level initialization are part of the behavior you need to test.
Running the whole script also exposes a common problem with selection-based testing: a fragment may work in a long-lived REPL only because a previous command created data that the real program would not have yet.
Execute One Notebook Cell or Fragment
Jupyter notebooks execute cells, not arbitrary source-file line ranges. The practical way to run “one line” is to put that statement and its necessary prerequisites in a small dedicated code cell.
def normalize(text):
return text.strip().lower()
Then put the call you want to test in another cell:
normalize(" Example Value ")
A notebook kernel keeps state just like a REPL. A cell may appear to work because a variable was defined in a different cell earlier in the session, even if that cell has since been edited or moved.
Before treating notebook output as reliable:
- Restart the kernel.
- Run the cells in intended order.
- Confirm that the target cell includes or follows all required imports and definitions.
- Use a fresh run before sharing the notebook or turning the code into a script.
Confirm the Fragment Works Without Hidden State
Use this short checklist after executing selected code:
- The selected code is syntactically complete.
- Every imported module, variable, and helper function is available.
- The output is correct, not merely free of errors.
- Re-running the selection will not duplicate an external side effect.
- The fragment works in a new REPL, fresh notebook kernel, or newly started program.
- The code has been moved into a function if you expect to run it again.
A fragment that only works after several unrelated commands is not yet self-contained. Make its dependencies explicit, then test it from a fresh Python session before relying on it in a script or automation.
For a quick experiment, send a self-contained fragment to a REPL. For repeatable execution, put the fragment in a function and call it.
Frequently Asked Questions
Can You Call a Python Script From a Specific Point?
Not reliably by source line number. Python scripts run top-level statements in order, and a later line may require variables, imports, or setup created earlier. Put the section you need into a function, then import and call that function directly.
How Do You Run Just One Line of Python Code?
Use the Python REPL when the line is a complete statement and its dependencies already exist. In VS Code, you can also disable Smart Send by setting python.REPL.enableREPLSmartSend to false, which makes cursor execution send only that physical line.
How Do You Bypass Certain Tasks in a Python Script?
Use functions and an explicit option, parameter, or conditional branch. For example, a write_output=False argument can skip an export step while still running loading and transformation steps in their required order.
Can You Run One Line From a Jupyter Notebook Cell?
The reliable approach is to move that statement into its own code cell, along with any required setup. A notebook cell can use values already stored in the kernel, so restart the kernel and rerun the needed cells to confirm that the line is not relying on hidden state.
What Does do Mean in Python?
Python has no do keyword or do...while loop. Use a while loop when code must repeat while a condition is true, or use a function when you want to name and run one specific operation.
