Run Your Multi-Line Python Code in a Single Line in the Python REPL
Run Your Multi-Line Python Code in a Single Line in the Python REPL
How to use exec to run multi-line Python in a single line
#Python #REPL #Coding #Programming
You’re in a browser. No terminal. No setup. Just a tiny Python REPL powered by Pyodide.
You type:
a, b = 0, 1
for i in range(10):
a, b = b, a + b
print(a)
Beautiful. It works. But… your REPL says:
“One line only, please.”
Now what?
Enter: exec() — your one-line superpower.
🔥 The Problem: Multi-Line Code, One-Line Limit
Many web-based REPLs (like those in tutorials, docs, or apps) only accept one line of input. That means no indented blocks. No multi-line functions. No joy.
But wait — there’s a way.
✅ The Fix: Wrap Code in exec()
exec() runs Python code from a string — and that string can contain newlines (\n) to simulate real structure.
So this:
a, b = 0, 1
for i in range(10):
a, b = b, a + b
print(a)
Becomes this one-liner:
exec("a, b = 0, 1\nfor i in range(10):\n a, b = b, a + b\n print(a)")
Boom. Multi-line logic. Single input. REPL unlocked.
🧠 Why This Works
\n= newline — tells Python “go to the next line” inside the string- Indentation? Use spaces (4 is best) — Python still sees it as valid
exec()parses the whole thing like real code
No magic. No hacks. Just pure Python, used cleverly.
🐍 Real Example: Fibonacci Friday
Want to generate the first 10 Fibonacci numbers in any REPL?
Just paste this:
exec("a, b = 0, 1\nfor i in range(10):\n a, b = b, a + b\n print(a)")
Output:
1
1
2
3
5
8
13
21
34
55
Perfect for sharing, teaching, or just feeling like a coding wizard at 2 AM.
💡 Pro Tips
- Use
iinstead of_for clarity in teaching - Avoid overwriting built-ins (like
range) - Test in steps: start with two lines, then grow
- Turn it into a Carbon image — dark theme, golden spiral overlay? Yes please.
🛠️ When to Use This
- Browser-based REPLs (Pyodide, JupyterLite, etc.)
- Chatbots or tools with one-line input
- Teaching Python in constrained environments
- Sharing runnable snippets on social media
exec() isn’t evil — it’s empowering, when used playfully and safely.
🚀 Final Thought
You don’t need a full IDE to write real Python.
You don’t need a terminal to run loops or logic.
All you need is exec() and a little creativity.
So go ahead — take your multi-line dreams, wrap them in a string, and run them anywhere.
Happy coding — one line at a time. 💻✨
Aaron Rose is a software engineer and technology writer at tech-reader.blog. For explainer videos and podcasts, check out Tech-Reader YouTube channel.
.png)

Comments
Post a Comment