Spaces:
Sleeping
Sleeping
import streamlit as st | |
import io | |
import sys | |
# Set up the layout of the app | |
st.title("Intro to Python: Interactive Learning") | |
st.write("Welcome to the Python learning platform! Explore the core concepts of Python programming with practical examples, and test them interactively.") | |
# Helper function to create an expanded explanation | |
def create_explanation(title, content): | |
with st.expander(f"Explanation: {title}"): | |
st.markdown(content) | |
# Helper function to execute code and capture output | |
def run_code(user_code): | |
# Create StringIO object to capture output | |
output = io.StringIO() | |
# Redirect stdout to capture print statements | |
sys.stdout = output | |
try: | |
# Execute the user's code | |
exec(user_code, {}) | |
# Return the captured output | |
result = output.getvalue() | |
return result, None | |
except Exception as e: | |
return None, str(e) | |
finally: | |
# Reset stdout | |
sys.stdout = sys.__stdout__ | |
# 1. Basic Syntax and Variables | |
st.subheader("1. Basic Syntax and Variables") | |
code1 = '''name = "Alice" | |
age = 25 | |
height = 5.6 | |
print(f"My name is {name}, I am {age} years old and {height} feet tall.") | |
''' | |
st.code(code1, language="python") | |
create_explanation("Basic Syntax and Variables", """ | |
In this example, we introduce **variables**, which are placeholders for storing data in Python. We create three variables: | |
- `name` stores a string (`"Alice"`), | |
- `age` stores an integer (`25`), | |
- `height` stores a float (`5.6`). | |
Next, we use **formatted string literals** (also known as f-strings) to combine these variables into a sentence and print it. The `print()` function outputs the message to the console. This is the fundamental way of creating variables and displaying information in Python. | |
""") | |
# Try it yourself box | |
st.write("### Try it Yourself:") | |
user_code1 = st.text_area("Example 1: Paste or modify the code and hit 'Run' to see the output.", value=code1, height=150, key="1") | |
if st.button("Run Example 1 Code"): | |
result, error = run_code(user_code1) | |
if result: | |
st.success("Code ran successfully!") | |
st.text(result) | |
elif error: | |
st.error(f"Error: {error}") | |
# 2. Control Flow: If-Else Statements | |
st.subheader("2. Control Flow: If-Else Statements") | |
code2 = '''temperature = 30 | |
if temperature > 25: | |
print("It's a hot day.") | |
else: | |
print("It's a cool day.") | |
''' | |
st.code(code2, language="python") | |
create_explanation("Control Flow: If-Else Statements", """ | |
**Control flow** allows you to make decisions in your code using conditions. The `if-else` statement checks if a condition is true: | |
- In this example, the condition is whether `temperature` is greater than `25`. | |
- If the condition is true, Python will execute the first block of code (`print("It's a hot day.")`). | |
- If the condition is false, Python executes the second block (`print("It's a cool day.")`). | |
Conditions use **comparison operators** like `>`, `<`, `==`, etc. Control flow is essential for writing dynamic, decision-based programs. | |
""") | |
# Try it yourself box | |
st.write("### Try it Yourself:") | |
user_code2 = st.text_area("Example 2: Paste or modify the code and hit 'Run' to see the output.", value=code2, height=150, key="2") | |
if st.button("Run Example 2 Code"): | |
result, error = run_code(user_code2) | |
if result: | |
st.success("Code ran successfully!") | |
st.text(result) | |
elif error: | |
st.error(f"Error: {error}") | |
# 3. Loops: For and While | |
st.subheader("3. Loops: For and While") | |
code3 = '''numbers = [1, 2, 3, 4, 5] | |
for number in numbers: | |
print(f"Number: {number}") | |
count = 5 | |
while count > 0: | |
print(f"Countdown: {count}") | |
count -= 1 | |
''' | |
st.code(code3, language="python") | |
create_explanation("Loops: For and While", """ | |
**Loops** allow you to repeat tasks. In this example, we demonstrate two types of loops: | |
- **For loop**: The `for` loop iterates over a list of numbers (`numbers`), printing each item in the list. This loop is commonly used when you know in advance how many times you want to iterate. | |
- **While loop**: The `while` loop continues as long as a specified condition is `True`. In this case, it counts down from `5` to `0`. This loop is useful when the number of iterations isn't known beforehand, but depends on a condition. | |
Loops are fundamental for automating repetitive tasks and processing sequences of data. | |
""") | |
# Try it yourself box | |
st.write("### Try it Yourself:") | |
user_code3 = st.text_area("Example 3: Paste or modify the code and hit 'Run' to see the output.", value=code3, height=150, key="3") | |
if st.button("Run Example 3 Code"): | |
result, error = run_code(user_code3) | |
if result: | |
st.success("Code ran successfully!") | |
st.text(result) | |
elif error: | |
st.error(f"Error: {error}") | |
# 4. Functions: Defining and Using Functions | |
st.subheader("4. Functions: Defining and Using Functions") | |
code4 = '''def add_numbers(a, b): | |
return a + b | |
result = add_numbers(10, 20) | |
print(f"The result is: {result}") | |
''' | |
st.code(code4, language="python") | |
create_explanation("Functions: Defining and Using Functions", """ | |
A **function** is a block of code that performs a specific task and can be reused multiple times. Functions allow us to structure our code for better readability and efficiency. Here's what's happening: | |
- We define a function `add_numbers(a, b)` which takes two arguments (`a` and `b`) and returns their sum. | |
- Then, we call this function with two numbers, `10` and `20`, and store the result in the variable `result`. | |
- Finally, we print the result. | |
Functions help make your code more modular and reusable by avoiding repetition. | |
""") | |
# Try it yourself box | |
st.write("### Try it Yourself:") | |
user_code4 = st.text_area("Example 4: Paste or modify the code and hit 'Run' to see the output.", value=code4, height=150, key="4") | |
if st.button("Run Example 4 Code"): | |
result, error = run_code(user_code4) | |
if result: | |
st.success("Code ran successfully!") | |
st.text(result) | |
elif error: | |
st.error(f"Error: {error}") | |
# 5. Lists and Dictionaries | |
st.subheader("5. Basic Data Structures: Lists and Dictionaries") | |
code5 = '''fruits = ["apple", "banana", "cherry"] | |
print(f"First fruit: {fruits[0]}") | |
student = {"name": "John", "age": 22, "major": "Computer Science"} | |
print(f"Student name: {student['name']}") | |
''' | |
st.code(code5, language="python") | |
create_explanation("Basic Data Structures: Lists and Dictionaries", """ | |
In Python, **data structures** are used to store and organize data. Two common structures are: | |
- **Lists**: Ordered collections of items (e.g., numbers, strings). You can access items by their index. In the example, `fruits[0]` retrieves the first item, `"apple"`. | |
- **Dictionaries**: Unordered collections of key-value pairs. In the example, `student['name']` retrieves the value associated with the key `'name'`, which is `"John"`. | |
These structures are essential for storing and managing data in your programs, and you’ll frequently use them in everyday coding. | |
""") | |
# Try it yourself box | |
st.write("### Try it Yourself:") | |
user_code5 = st.text_area("Example 5: Paste or modify the code and hit 'Run' to see the output.", value=code5, height=150, key="5") | |
if st.button("Run Example 5 Code"): | |
result, error = run_code(user_code5) | |
if result: | |
st.success("Code ran successfully!") | |
st.text(result) | |
elif error: | |
st.error(f"Error: {error}") | |
# Footer | |
st.write("This app is an educational tool to help you learn basic Python concepts. Keep exploring and practicing to master the language!") | |