A simple python code editor that displays the output of the code by eval
To upload files, please first save the app
import streamlit as st
st.title("Python Code Editor")
# Initialize session state for code if not exists
if 'code' not in st.session_state:
st.session_state.code = '''# Enter your Python code here
print("Hello, World!")
x = 5
y = 10
print(f"Sum of {x} and {y} is {x + y}")'''
# Code editor
code = st.text_area("Enter your Python code:", value=st.session_state.code, height=200)
st.session_state.code = code
# Execute button
if st.button("Run Code"):
try:
st.write("Output:")
# Create a code block for output
with st.code(""):
# Redirect stdout to capture print statements
import sys
from io import StringIO
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()
# Execute the code
exec(code)
# Restore stdout and get output
sys.stdout = old_stdout
output = mystdout.getvalue()
# Display the output
st.code(output)
# Try to get the last expression result
try:
result = eval(code.split('\n')[-1])
if result is not None:
st.write("Last Expression Result:")
st.write(result)
except:
pass
except Exception as e:
st.error(f"Error: {str(e)}")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?