eaglelandsonce commited on
Commit
3903944
·
verified ·
1 Parent(s): 9f361a6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +398 -0
app.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import io
3
+ import contextlib
4
+ import traceback
5
+
6
+
7
+ # ---------- Python runner ----------
8
+
9
+ def run_python(code: str) -> str:
10
+ """
11
+ Execute user-provided Python code and capture stdout / errors.
12
+ NOTE: This is for teaching demos; do NOT use this pattern in
13
+ a multi-user production environment without sandboxing.
14
+ """
15
+ stdout_buffer = io.StringIO()
16
+ try:
17
+ # Provide a very simple, mostly empty environment
18
+ local_env = {}
19
+ global_env = {"__builtins__": __builtins__}
20
+
21
+ with contextlib.redirect_stdout(stdout_buffer):
22
+ exec(code, global_env, local_env)
23
+
24
+ output = stdout_buffer.getvalue()
25
+ if not output.strip():
26
+ output = "[No output produced]"
27
+ return output
28
+ except Exception:
29
+ error_text = stdout_buffer.getvalue()
30
+ error_text += "\n" + traceback.format_exc()
31
+ return error_text
32
+
33
+
34
+ # ---------- Course content ----------
35
+
36
+ lessons = [
37
+ {
38
+ "title": "Lesson 1: Setup & Simple Apps",
39
+ "description": """
40
+ ### Lesson 1: Setting Up Python and Developing a Simple Application
41
+
42
+ **Topics**
43
+ - Topic A: Set Up the Development Environment
44
+ - Topic B: Write Python Statements
45
+ - Topic C: Create a Python Application
46
+ - Topic D: Prevent Errors
47
+
48
+ Use this tab to practice basic `print`, variables, and simple input/output.
49
+ You can modify the starter code below or paste your own.
50
+ """,
51
+ "starter_code": '''# Lesson 1: Simple Hello & Input
52
+
53
+ print("👋 Welcome to Lesson 1: Setup & Simple Apps")
54
+
55
+ name = input("What is your name? ")
56
+ age = input("How old are you? ")
57
+
58
+ print(f"Hello, {name}! You are {age} years old.")
59
+
60
+ # Try:
61
+ # 1. Add two numbers entered by the user.
62
+ # 2. Print a message that includes that sum.
63
+ '''
64
+ },
65
+ {
66
+ "title": "Lesson 2: Simple Data Types",
67
+ "description": """
68
+ ### Lesson 2: Processing Simple Data Types
69
+
70
+ **Topics**
71
+ - Topic A: Process Strings and Integers
72
+ - Topic B: Process Decimals, Floats, and Mixed Number Types
73
+
74
+ Practice working with strings, integers, and floats.
75
+ Try changing the values and adding your own calculations.
76
+ """,
77
+ "starter_code": '''# Lesson 2: Strings, Integers, Floats
78
+
79
+ print("✨ Lesson 2: Simple Data Types")
80
+
81
+ first_name = "Alice"
82
+ last_name = "Smith"
83
+ age = 30
84
+ height_m = 1.70
85
+ weight_kg = 65.0
86
+
87
+ full_name = first_name + " " + last_name
88
+ bmi = weight_kg / (height_m ** 2)
89
+
90
+ print("Full name:", full_name)
91
+ print("Age next year:", age + 1)
92
+ print("BMI (unrounded):", bmi)
93
+ print("BMI (rounded to 2 decimals):", round(bmi, 2))
94
+
95
+ # Try:
96
+ # 1. Ask the user for their name and birth year and compute their age.
97
+ # 2. Convert a temperature from Fahrenheit to Celsius.
98
+ '''
99
+ },
100
+ {
101
+ "title": "Lesson 3: Data Structures",
102
+ "description": """
103
+ ### Lesson 3: Processing Data Structures
104
+
105
+ **Topics**
106
+ - Topic A: Process Ordered Data Structures (lists, tuples)
107
+ - Topic B: Process Unordered Data Structures (sets, dictionaries)
108
+
109
+ Use this tab to experiment with lists, tuples, sets, and dictionaries.
110
+ """,
111
+ "starter_code": '''# Lesson 3: Lists, Tuples, Sets, Dictionaries
112
+
113
+ print("📚 Lesson 3: Data Structures")
114
+
115
+ # Ordered: lists and tuples
116
+ fruits = ["apple", "banana", "cherry"]
117
+ scores = (88, 92, 79)
118
+
119
+ print("Fruits:", fruits)
120
+ print("First fruit:", fruits[0])
121
+ print("Scores:", scores)
122
+ print("Average score:", sum(scores) / len(scores))
123
+
124
+ # Unordered: sets and dictionaries
125
+ numbers_with_duplicates = [1, 2, 2, 3, 3, 3]
126
+ unique_numbers = set(numbers_with_duplicates)
127
+
128
+ print("Original numbers:", numbers_with_duplicates)
129
+ print("Unique numbers:", unique_numbers)
130
+
131
+ student = {
132
+ "name": "Alice",
133
+ "age": 20,
134
+ "grade": "A"
135
+ }
136
+
137
+ print("Student name:", student["name"])
138
+
139
+ print("\\nAll student key/value pairs:")
140
+ for key, value in student.items():
141
+ print(f"{key}: {value}")
142
+
143
+ # Try:
144
+ # 1. Add a new key "major" to the student dictionary.
145
+ # 2. Create a list of 5 movies and print the first and last.
146
+ '''
147
+ },
148
+ {
149
+ "title": "Lesson 4: Conditionals & Loops",
150
+ "description": """
151
+ ### Lesson 4: Writing Conditional Statements and Loops
152
+
153
+ **Topics**
154
+ - Topic A: Write a Conditional Statement (`if`, `elif`, `else`)
155
+ - Topic B: Write a Loop (`for`, `while`)
156
+
157
+ Use this tab to build branching logic and repeated actions.
158
+ """,
159
+ "starter_code": '''# Lesson 4: Conditionals & Loops
160
+
161
+ print("🔁 Lesson 4: Conditionals and Loops")
162
+
163
+ # Conditional example
164
+ score = int(input("Enter a score between 0 and 100: "))
165
+
166
+ if score >= 90:
167
+ grade = "A"
168
+ elif score >= 80:
169
+ grade = "B"
170
+ elif score >= 70:
171
+ grade = "C"
172
+ elif score >= 60:
173
+ grade = "D"
174
+ else:
175
+ grade = "F"
176
+
177
+ print(f"Your grade is: {grade}")
178
+
179
+ # Loop example: print even numbers 2-20
180
+ print("\\nEven numbers from 2 to 20:")
181
+ for n in range(2, 21, 2):
182
+ print(n, end=" ")
183
+
184
+ print() # newline
185
+
186
+ # Try:
187
+ # 1. Use a while loop to ask for a password until it is 'secret'.
188
+ # 2. Write an if/elif/else to classify a number as positive, negative, or zero.
189
+ '''
190
+ },
191
+ {
192
+ "title": "Lesson 5: Functions, Classes, Modules",
193
+ "description": """
194
+ ### Lesson 5: Structuring Code for Reuse
195
+
196
+ **Topics**
197
+ - Topic A: Define and Call a Function
198
+ - Topic B: Define and Instantiate a Class
199
+ - Topic C: Import and Use a Module
200
+
201
+ Use this tab to practice writing functions, basic classes, and using modules.
202
+ """,
203
+ "starter_code": '''# Lesson 5: Functions, Classes, and Modules
204
+
205
+ print("🧩 Lesson 5: Reusable Code")
206
+
207
+ # --- Functions ---
208
+
209
+ def add(a, b):
210
+ """Return the sum of a and b."""
211
+ return a + b
212
+
213
+ result = add(10, 5)
214
+ print("10 + 5 =", result)
215
+
216
+
217
+ # --- Classes ---
218
+
219
+ class Car:
220
+ def __init__(self, make, model, year):
221
+ self.make = make
222
+ self.model = model
223
+ self.year = year
224
+
225
+ def description(self):
226
+ return f"{self.year} {self.make} {self.model}"
227
+
228
+ my_car = Car("Toyota", "Corolla", 2022)
229
+ print("My car:", my_car.description())
230
+
231
+
232
+ # --- Modules ---
233
+
234
+ import math
235
+ import random
236
+
237
+ print("Square root of 16:", math.sqrt(16))
238
+ print("Random integer from 1 to 6:", random.randint(1, 6))
239
+
240
+ # Try:
241
+ # 1. Write a function is_even(n) that returns True if n is even.
242
+ # 2. Create a BankAccount class with deposit and withdraw methods.
243
+ '''
244
+ },
245
+ {
246
+ "title": "Lesson 6: Files & Directories",
247
+ "description": """
248
+ ### Lesson 6: Writing Code to Process Files and Directories
249
+
250
+ **Topics**
251
+ - Topic A: Write to a Text File
252
+ - Topic B: Read from a Text File
253
+ - Topic C: Get the Contents of a Directory
254
+ - Topic D: Manage Files and Directories
255
+
256
+ ⚠️ For safety: in a hosted environment, file access is temporary and sandboxed.
257
+ Use this to learn the basics of reading and writing files.
258
+ """,
259
+ "starter_code": '''# Lesson 6: Files & Directories
260
+
261
+ print("📂 Lesson 6: Files and Directories")
262
+
263
+ from pathlib import Path
264
+
265
+ # Create a folder
266
+ folder = Path("demo_folder")
267
+ folder.mkdir(exist_ok=True)
268
+
269
+ # Write to a file
270
+ file_path = folder / "example.txt"
271
+ file_path.write_text("Hello from Lesson 6!\\nThis is a test file.")
272
+
273
+ print("Wrote file:", file_path)
274
+
275
+ # Read from a file
276
+ content = file_path.read_text()
277
+ print("\\nFile contents:")
278
+ print(content)
279
+
280
+ # List directory contents
281
+ print("\\nContents of demo_folder:")
282
+ for item in folder.iterdir():
283
+ print(" -", item.name)
284
+
285
+ # Try:
286
+ # 1. Add another file with different text.
287
+ # 2. Read both files and print their contents.
288
+ '''
289
+ },
290
+ {
291
+ "title": "Lesson 7: Exceptions",
292
+ "description": """
293
+ ### Lesson 7: Dealing with Exceptions
294
+
295
+ **Topics**
296
+ - Topic A: Handle Exceptions
297
+ - Topic B: Raise Exceptions
298
+
299
+ Use this tab to practice `try/except` and raising your own exceptions.
300
+ """,
301
+ "starter_code": '''# Lesson 7: Exceptions
302
+
303
+ print("⚠️ Lesson 7: Exceptions")
304
+
305
+ def safe_divide(a, b):
306
+ try:
307
+ return a / b
308
+ except ZeroDivisionError:
309
+ print("Error: cannot divide by zero!")
310
+ return None
311
+
312
+ x = float(input("Enter numerator: "))
313
+ y = float(input("Enter denominator: "))
314
+ result = safe_divide(x, y)
315
+
316
+ print("Result:", result)
317
+
318
+ # Raising your own exception
319
+ def set_age(age):
320
+ if age < 0 or age > 120:
321
+ raise ValueError("Age must be between 0 and 120.")
322
+ return age
323
+
324
+ try:
325
+ age_value = int(input("Enter an age (0-120): "))
326
+ print("Valid age:", set_age(age_value))
327
+ except ValueError as e:
328
+ print("Invalid age:", e)
329
+
330
+ # Try:
331
+ # 1. Wrap more user input in try/except to catch ValueError.
332
+ # 2. Write a function that raises ValueError if a discount is not between 0 and 100.
333
+ '''
334
+ },
335
+ ]
336
+
337
+ appendix_markdown = r"""
338
+ ## 📎 References & Appendices
339
+
340
+ This tab consolidates extra reference material for the course.
341
+
342
+ ---
343
+
344
+ ### Appendix A: Major Differences Between Python 2 and 3
345
+
346
+ Modern development uses **Python 3**, but here are some historical differences:
347
+
348
+ - `print`
349
+ - Python 2: `print "Hello"`
350
+ - Python 3: `print("Hello")`
351
+ - Integer division
352
+ - Python 2: `5/2` → `2` (integer when both are ints)
353
+ - Python 3: `5/2` → `2.5`, use `5//2` for integer division.
354
+ - Text and bytes
355
+ - Python 2: `str` (bytes) vs `unicode`.
356
+ - Python 3: `str` is Unicode by default; `bytes` is a separate type.
357
+ - `input()`
358
+ - Python 2: `input()` evaluates, `raw_input()` returns string.
359
+ - Python 3: `input()` always returns a string.
360
+ - Standard library layout
361
+ - Some modules reorganized (e.g., `urllib` family).
362
+
363
+ If you’re starting now, you almost never need Python 2, but you might see old code in the wild.
364
+
365
+ ---
366
+
367
+ ### Appendix B: Mini Python Style Guide (PEP 8 Highlights)
368
+
369
+ Follow these conventions to keep your code clean and readable:
370
+
371
+ **Indentation**
372
+ - Use **4 spaces** per indentation level.
373
+ - Avoid mixing tabs and spaces.
374
+
375
+ **Naming**
376
+ - Variables / functions: `snake_case` (e.g., `total_price`, `calculate_bmi`).
377
+ - Classes: `CapWords` (e.g., `BankAccount`).
378
+ - Constants: `UPPER_CASE` (e.g., `PI = 3.14159`).
379
+
380
+ **Spacing**
381
+ - Around operators: `x = a + b`, not `x=a+b`.
382
+ - After commas: `func(a, b, c)`.
383
+
384
+ **Imports**
385
+ - At the **top** of the file.
386
+ - One import per line is preferred.
387
+
388
+ **Comments & Docstrings**
389
+ - Use `#` for short explanations above a line or block.
390
+ - Use triple-quoted strings `"""Docs here"""` for functions, classes, and modules.
391
+
392
+ **Structure**
393
+ - Break large scripts into functions and classes.
394
+ - For larger programs, use
395
+
396
+ ```python
397
+ if __name__ == "__main__":
398
+ main()