eaglelandsonce commited on
Commit
68aba08
·
verified ·
1 Parent(s): 6b43df8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -24
app.py CHANGED
@@ -1,16 +1,15 @@
1
  import streamlit as st
2
- import streamlit.components.v1 as components
3
 
4
  # Set up the layout of the app
5
  st.title("Intro to Python: Interactive Learning")
6
- st.write("Welcome to the Python learning platform. Below are key examples to help you get started with Python programming.")
7
 
8
- # Helper function to create an expandable explanation
9
  def create_explanation(title, content):
10
  with st.expander(f"Explanation: {title}"):
11
- st.write(content)
12
 
13
- # Example 1: Basic Syntax and Variables
14
  st.subheader("1. Basic Syntax and Variables")
15
  code1 = '''name = "Alice"
16
  age = 25
@@ -19,9 +18,29 @@ height = 5.6
19
  print(f"My name is {name}, I am {age} years old and {height} feet tall.")
20
  '''
21
  st.code(code1, language="python")
22
- create_explanation("Basic Syntax", "This example shows how to assign values to variables, different data types, and how to print a formatted string.")
23
 
24
- # Example 2: If-Else Condition
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  st.subheader("2. Control Flow: If-Else Statements")
26
  code2 = '''temperature = 30
27
 
@@ -31,9 +50,29 @@ else:
31
  print("It's a cool day.")
32
  '''
33
  st.code(code2, language="python")
34
- create_explanation("If-Else", "This example demonstrates how to use conditional logic in Python to make decisions based on conditions.")
35
 
36
- # Example 3: For and While Loops
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  st.subheader("3. Loops: For and While")
38
  code3 = '''numbers = [1, 2, 3, 4, 5]
39
  for number in numbers:
@@ -45,9 +84,28 @@ while count > 0:
45
  count -= 1
46
  '''
47
  st.code(code3, language="python")
48
- create_explanation("Loops", "Loops are used to repeat tasks. A 'for' loop iterates over a list, and a 'while' loop repeats until a condition becomes false.")
49
 
50
- # Example 4: Functions
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  st.subheader("4. Functions: Defining and Using Functions")
52
  code4 = '''def add_numbers(a, b):
53
  return a + b
@@ -56,9 +114,29 @@ result = add_numbers(10, 20)
56
  print(f"The result is: {result}")
57
  '''
58
  st.code(code4, language="python")
59
- create_explanation("Functions", "Functions allow you to define reusable blocks of code. In this example, a function adds two numbers.")
60
 
61
- # Example 5: Lists and Dictionaries
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  st.subheader("5. Basic Data Structures: Lists and Dictionaries")
63
  code5 = '''fruits = ["apple", "banana", "cherry"]
64
  print(f"First fruit: {fruits[0]}")
@@ -67,22 +145,26 @@ student = {"name": "John", "age": 22, "major": "Computer Science"}
67
  print(f"Student name: {student['name']}")
68
  '''
69
  st.code(code5, language="python")
70
- create_explanation("Lists and Dictionaries", "Lists hold sequences of items, and dictionaries store data as key-value pairs.")
71
 
72
- # Interactive code execution section
73
- st.subheader("Try It Yourself: Python Code Simulation")
74
- user_code = st.text_area("Paste your Python code below and hit 'Run' to see the output.", height=150)
 
 
 
 
 
 
 
 
75
 
76
- if st.button("Run Code"):
77
  try:
78
- # Capture and display the output of the user's code
79
  exec_locals = {}
80
- exec(user_code, {}, exec_locals)
81
  st.success("Code ran successfully!")
82
- output = exec_locals
83
- st.write(output)
84
  except Exception as e:
85
  st.error(f"Error: {str(e)}")
86
 
87
- # Educational footer
88
- st.write("This app is an educational tool to help you learn basic Python concepts. Keep exploring and practicing!")
 
1
  import streamlit as st
 
2
 
3
  # Set up the layout of the app
4
  st.title("Intro to Python: Interactive Learning")
5
+ st.write("Welcome to the Python learning platform! Explore the core concepts of Python programming with practical examples, and test them interactively.")
6
 
7
+ # Helper function to create an expanded explanation
8
  def create_explanation(title, content):
9
  with st.expander(f"Explanation: {title}"):
10
+ st.markdown(content)
11
 
12
+ # 1. Basic Syntax and Variables
13
  st.subheader("1. Basic Syntax and Variables")
14
  code1 = '''name = "Alice"
15
  age = 25
 
18
  print(f"My name is {name}, I am {age} years old and {height} feet tall.")
19
  '''
20
  st.code(code1, language="python")
 
21
 
22
+ create_explanation("Basic Syntax and Variables", """
23
+ In this example, we introduce **variables**, which are placeholders for storing data in Python. We create three variables:
24
+ - `name` stores a string (`"Alice"`),
25
+ - `age` stores an integer (`25`),
26
+ - `height` stores a float (`5.6`).
27
+
28
+ 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.
29
+ """)
30
+
31
+ # Try it yourself box
32
+ st.write("### Try it Yourself:")
33
+ 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")
34
+
35
+ if st.button("Run Example 1 Code"):
36
+ try:
37
+ exec_locals = {}
38
+ exec(user_code1, {}, exec_locals)
39
+ st.success("Code ran successfully!")
40
+ except Exception as e:
41
+ st.error(f"Error: {str(e)}")
42
+
43
+ # 2. Control Flow: If-Else Statements
44
  st.subheader("2. Control Flow: If-Else Statements")
45
  code2 = '''temperature = 30
46
 
 
50
  print("It's a cool day.")
51
  '''
52
  st.code(code2, language="python")
 
53
 
54
+ create_explanation("Control Flow: If-Else Statements", """
55
+ **Control flow** allows you to make decisions in your code using conditions. The `if-else` statement checks if a condition is true:
56
+ - In this example, the condition is whether `temperature` is greater than `25`.
57
+ - If the condition is true, Python will execute the first block of code (`print("It's a hot day.")`).
58
+ - If the condition is false, Python executes the second block (`print("It's a cool day.")`).
59
+
60
+ Conditions use **comparison operators** like `>`, `<`, `==`, etc. Control flow is essential for writing dynamic, decision-based programs.
61
+ """)
62
+
63
+ # Try it yourself box
64
+ st.write("### Try it Yourself:")
65
+ 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")
66
+
67
+ if st.button("Run Example 2 Code"):
68
+ try:
69
+ exec_locals = {}
70
+ exec(user_code2, {}, exec_locals)
71
+ st.success("Code ran successfully!")
72
+ except Exception as e:
73
+ st.error(f"Error: {str(e)}")
74
+
75
+ # 3. Loops: For and While
76
  st.subheader("3. Loops: For and While")
77
  code3 = '''numbers = [1, 2, 3, 4, 5]
78
  for number in numbers:
 
84
  count -= 1
85
  '''
86
  st.code(code3, language="python")
 
87
 
88
+ create_explanation("Loops: For and While", """
89
+ **Loops** allow you to repeat tasks. In this example, we demonstrate two types of loops:
90
+ - **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.
91
+ - **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.
92
+
93
+ Loops are fundamental for automating repetitive tasks and processing sequences of data.
94
+ """)
95
+
96
+ # Try it yourself box
97
+ st.write("### Try it Yourself:")
98
+ 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")
99
+
100
+ if st.button("Run Example 3 Code"):
101
+ try:
102
+ exec_locals = {}
103
+ exec(user_code3, {}, exec_locals)
104
+ st.success("Code ran successfully!")
105
+ except Exception as e:
106
+ st.error(f"Error: {str(e)}")
107
+
108
+ # 4. Functions: Defining and Using Functions
109
  st.subheader("4. Functions: Defining and Using Functions")
110
  code4 = '''def add_numbers(a, b):
111
  return a + b
 
114
  print(f"The result is: {result}")
115
  '''
116
  st.code(code4, language="python")
 
117
 
118
+ create_explanation("Functions: Defining and Using Functions", """
119
+ 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:
120
+ - We define a function `add_numbers(a, b)` which takes two arguments (`a` and `b`) and returns their sum.
121
+ - Then, we call this function with two numbers, `10` and `20`, and store the result in the variable `result`.
122
+ - Finally, we print the result.
123
+
124
+ Functions help make your code more modular and reusable by avoiding repetition.
125
+ """)
126
+
127
+ # Try it yourself box
128
+ st.write("### Try it Yourself:")
129
+ 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")
130
+
131
+ if st.button("Run Example 4 Code"):
132
+ try:
133
+ exec_locals = {}
134
+ exec(user_code4, {}, exec_locals)
135
+ st.success("Code ran successfully!")
136
+ except Exception as e:
137
+ st.error(f"Error: {str(e)}")
138
+
139
+ # 5. Lists and Dictionaries
140
  st.subheader("5. Basic Data Structures: Lists and Dictionaries")
141
  code5 = '''fruits = ["apple", "banana", "cherry"]
142
  print(f"First fruit: {fruits[0]}")
 
145
  print(f"Student name: {student['name']}")
146
  '''
147
  st.code(code5, language="python")
 
148
 
149
+ create_explanation("Basic Data Structures: Lists and Dictionaries", """
150
+ In Python, **data structures** are used to store and organize data. Two common structures are:
151
+ - **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"`.
152
+ - **Dictionaries**: Unordered collections of key-value pairs. In the example, `student['name']` retrieves the value associated with the key `'name'`, which is `"John"`.
153
+
154
+ These structures are essential for storing and managing data in your programs, and you’ll frequently use them in everyday coding.
155
+ """)
156
+
157
+ # Try it yourself box
158
+ st.write("### Try it Yourself:")
159
+ 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")
160
 
161
+ if st.button("Run Example 5 Code"):
162
  try:
 
163
  exec_locals = {}
164
+ exec(user_code5, {}, exec_locals)
165
  st.success("Code ran successfully!")
 
 
166
  except Exception as e:
167
  st.error(f"Error: {str(e)}")
168
 
169
+ # Footer
170
+ st.write("This app is an educational tool to help you learn basic Python concepts. Keep exploring and practicing to master the language!")