Spaces:
Sleeping
Sleeping
File size: 7,562 Bytes
6b43df8 93cfcaa 6b43df8 68aba08 6b43df8 68aba08 6b43df8 68aba08 6b43df8 93cfcaa 68aba08 6b43df8 68aba08 93cfcaa 68aba08 93cfcaa 68aba08 6b43df8 68aba08 93cfcaa 68aba08 93cfcaa 68aba08 6b43df8 68aba08 93cfcaa 68aba08 93cfcaa 68aba08 6b43df8 68aba08 93cfcaa 68aba08 93cfcaa 68aba08 6b43df8 68aba08 6b43df8 68aba08 93cfcaa 6b43df8 93cfcaa 6b43df8 68aba08 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
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!")
|