File size: 15,222 Bytes
63a7f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847a8e
63a7f01
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
63a7f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847a8e
63a7f01
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
63a7f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847a8e
63a7f01
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
63a7f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847a8e
63a7f01
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a7f01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
63a7f01
 
 
 
 
 
5847a8e
63a7f01
 
5847a8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63a7f01
 
 
 
 
5847a8e
 
 
 
 
 
 
 
 
 
63a7f01
 
fb62875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88ff3a0
 
 
 
 
 
 
 
 
fb62875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import streamlit as st
import numpy as np
import plotly.graph_objects as go
import io
import sys
import pandas as pd
from contextlib import redirect_stdout
import matplotlib.pyplot as plt
import seaborn as sns

# Initialize session state for notebook-like cells
if 'cells' not in st.session_state:
    st.session_state.cells = []
if 'df' not in st.session_state:
    st.session_state.df = None

def capture_output(code, df=None):
    """Helper function to capture print output"""
    f = io.StringIO()
    with redirect_stdout(f):
        try:
            # Create a dictionary of variables to use in exec
            variables = {'pd': pd, 'np': np, 'plt': plt, 'sns': sns}
            if df is not None:
                variables['df'] = df
            exec(code, variables)
        except Exception as e:
            return f"Error: {str(e)}"
    return f.getvalue()

def show():
    st.markdown("""
    ## Week 2: Python Basics - Part 1: Coding Exercises
    
    In this first part, we'll learn some fundamental Python concepts through hands-on exercises:
    - Importing libraries
    - Using print statements
    - Basic arithmetic operations
    - Working with lists
    """)
    
    # Importing Libraries Section
    st.header("1. Importing Libraries")
    st.markdown("""
    Python has a rich ecosystem of libraries. To use them, we need to import them first.
    """)
    
    with st.expander("Import Example"):
        st.code("""
    # Importing a library
    import math
    
    # Using a function from the library
    print(math.sqrt(16))  # This will print 4.0
        """, language="python", line_numbers=True)
    
    # Interactive Import Exercise
    st.subheader("Try it yourself!")
    import_code = st.text_area("Try importing and using the math library:", 
                             "import math\nprint(math.sqrt(25))", 
                             height=100)
    st.code(import_code, language="python", line_numbers=True)
    if st.button("Run Import Code"):
        output = capture_output(import_code)
        st.code(output, language="python", line_numbers=True)
    
    # Print Statements Section
    st.header("2. Print Statements")
    st.markdown("""
    The print() function is used to display output to the console.
    """)
    
    with st.expander("Print Examples"):
        st.code("""
    # Basic print
    print("Hello, World!")
    
    # Print with variables
    name = "Alice"
    print(f"Hello, {name}!")
    
    # Print multiple items
    print("The answer is:", 42)
        """, language="python", line_numbers=True)
    
    # Interactive Print Exercise
    st.subheader("Try it yourself!")
    print_code = st.text_area("Try some print statements:", 
                            'print("Hello, World!")\nname = "Python"\nprint(f"Hello, {name}!")', 
                            height=100)
    st.code(print_code, language="python", line_numbers=True)
    if st.button("Run Print Code"):
        output = capture_output(print_code)
        st.code(output, language="python", line_numbers=True)
    
    # Basic Arithmetic Section
    st.header("3. Basic Arithmetic")
    st.markdown("""
    Python can perform basic mathematical operations.
    """)
    
    with st.expander("Arithmetic Examples"):
        st.code("""
    # Addition
    result = 5 + 3
    print(result)  # Prints 8
    
    # Subtraction
    result = 10 - 4
    print(result)  # Prints 6
    
    # Multiplication
    result = 6 * 7
    print(result)  # Prints 42
    
    # Division
    result = 15 / 3
    print(result)  # Prints 5.0
        """, language="python", line_numbers=True)
    
    # Interactive Arithmetic Exercise
    st.subheader("Try it yourself!")
    arithmetic_code = st.text_area("Try some arithmetic operations:", 
                                 'print(5 + 3)\nprint(10 - 4)\nprint(6 * 7)\nprint(15 / 3)', 
                                 height=100)
    st.code(arithmetic_code, language="python", line_numbers=True)
    if st.button("Run Arithmetic Code"):
        output = capture_output(arithmetic_code)
        st.code(output, language="python", line_numbers=True)
    
    # Lists Section
    st.header("4. Lists")
    st.markdown("""
    Lists are used to store multiple items in a single variable.
    """)
    
    with st.expander("List Examples"):
        st.code("""
    # Creating a list
    fruits = ["apple", "banana", "cherry"]
    
    # Accessing list items
    print(fruits[0])  # Prints "apple"
    
    # Adding to a list
    fruits.append("orange")
    print(fruits)  # Prints ["apple", "banana", "cherry", "orange"]
    
    # List length
    print(len(fruits))  # Prints 4
        """, language="python", line_numbers=True)
    
    # Interactive List Exercise
    st.subheader("Try it yourself!")
    list_code = st.text_area("Try working with lists:", 
                           'fruits = ["apple", "banana", "cherry"]\nprint(fruits[0])\nfruits.append("orange")\nprint(fruits)\nprint(len(fruits))', 
                           height=100)
    st.code(list_code, language="python", line_numbers=True)
    if st.button("Run List Code"):
        output = capture_output(list_code)
        st.code(output, language="python", line_numbers=True)
    
    # Loops Section
    st.header("5. Loops")
    st.markdown("""
    Loops are used to repeat a block of code multiple times. Python has two main types of loops:
    - `for` loops: Used to iterate over a sequence (like a list, string, or range)
    - `while` loops: Used to repeat code while a condition is true
    """)
    
    with st.expander("For Loop Examples"):
        st.code("""
    # Basic for loop
    fruits = ["apple", "banana", "cherry"]
    for fruit in fruits:
        print(fruit)
    
    # For loop with range
    for i in range(5):  # Prints numbers 0 to 4
        print(i)
    
    # For loop with index
    for i, fruit in enumerate(fruits):
        print(f"Index {i}: {fruit}")
        """, language="python", line_numbers=True)
    
    with st.expander("While Loop Examples"):
        st.code("""
    # Basic while loop
    count = 0
    while count < 5:
        print(count)
        count += 1
    
    # While loop with break
    while True:
        user_input = input("Enter 'quit' to exit: ")
        if user_input == 'quit':
            break
        print(f"You entered: {user_input}")
        """, language="python", line_numbers=True)
    
    # Interactive Loop Exercise
    st.subheader("Try it yourself!")
    st.markdown("""
    Try these exercises:
    1. Create a for loop that prints numbers from 1 to 10
    2. Create a while loop that counts down from 5 to 1
    3. Use a for loop to print each letter in your name
    """)
    
    loop_code = st.text_area("Write your loop code here:", 
                           '# Exercise 1\nfor i in range(1, 11):\n    print(i)\n\n# Exercise 2\ncount = 5\nwhile count > 0:\n    print(count)\n    count -= 1\n\n# Exercise 3\nname = "Python"\nfor letter in name:\n    print(letter)', 
                           height=150)
    st.code(loop_code, language="python", line_numbers=True)
    if st.button("Run Loop Code"):
        output = capture_output(loop_code)
        st.code(output, language="python", line_numbers=True)
    
    # Practice Exercise
    st.header("Practice Exercise")
    st.markdown("""
    ### Try this exercise:
    Create a program that:
    1. Imports the math library
    2. Creates a list of numbers
    3. Uses a loop to print each number and its square root
    """)
    
    # Interactive Practice Exercise
    st.subheader("Try your solution!")
    practice_code = st.text_area("Write your solution here:", 
                               'import math\n\nnumbers = [4, 9, 16, 25]\n\nfor num in numbers:\n    print(f"Number: {num}, Square root: {math.sqrt(num)}")', 
                               height=150)
    st.code(practice_code, language="python", line_numbers=True)
    if st.button("Run Practice Code"):
        output = capture_output(practice_code)
        st.code(output, language="python", line_numbers=True)
    
    st.markdown("""
    ## Part 2: Data Cleaning Lab
    
    In this lab, we'll learn how to clean and prepare data using pandas. We'll work with the Advertising dataset and practice common data cleaning techniques.
    
    Let's start with some basic examples of working with data in pandas:
    """)

    # Example 1: Reading CSV from URL
    st.header("Example 1: Reading CSV from URL")
    st.markdown("""
    There are several ways to read a CSV file from a URL using pandas. Here are some examples:
    """)
    
    with st.expander("Method 1: Using pandas.read_csv()"):
        st.code("""
    import pandas as pd
    
    # Method 1: Direct URL
    url = "https://www.statlearning.com/s/Advertising.csv"
    df = pd.read_csv(url)
    print(df.head())
        """, line_numbers=True)
    
    with st.expander("Method 2: Using requests and StringIO"):
        st.code("""
    import pandas as pd
    import requests
    from io import StringIO
    
    # Method 2: Using requests
    url = "https://www.statlearning.com/s/Advertising.csv"
    response = requests.get(url)
    data = StringIO(response.text)
    df = pd.read_csv(data)
    print(df.head())
        """, line_numbers=True)
    
    # Example 2: Answering Questions about the Dataset
    st.header("Example 2: Answering Questions about the Dataset")
    st.markdown("""
    Once we have loaded our data, we can answer various questions about it. Here are some common questions and how to answer them:
    """)
    
    with st.expander("Question 1: How many rows and columns are in the dataset?"):
        st.code("""
    # Get the shape of the dataframe
    print(f"Number of rows: {df.shape[0]}")
    print(f"Number of columns: {df.shape[1]}")
        """, line_numbers=True)
    
    with st.expander("Question 2: What are the column names and data types?"):
        st.code("""
    # Get column names
    print("Column names:")
    print(df.columns.tolist())
    
    # Get data types
    print("\nData types:")
    print(df.dtypes)
        """, line_numbers=True)
    
    with st.expander("Question 3: What are the basic statistics of numerical columns?"):
        st.code("""
    # Get descriptive statistics
    print(df.describe())
        """, line_numbers=True)
    
    with st.expander("Question 4: Are there any missing values?"):
        st.code("""
    # Check for missing values
    print("Missing values per column:")
    print(df.isnull().sum())
        """, line_numbers=True)
    
    with st.expander("Question 5: What are the unique values in categorical columns?"):
        st.code("""
    # For each column, print unique values
    for column in df.select_dtypes(include=['object']).columns:
        print(f"\nUnique values in {column}:")
        print(df[column].unique())
        """, line_numbers=True)
    
    # Interactive Exercise
    st.header("Try it yourself!")
    st.markdown("""
    Now it's your turn to try these examples. Use the code editor below to:
    1. Load the Advertising dataset from the URL
    2. Answer the questions above about the dataset
    """)
    
    # Code editor for interactive exercise
    exercise_code = st.text_area("Write your code here:", 
                               'import pandas as pd\n\n# Your code here', 
                               height=200)
    
    if st.button("Run Code"):
        output = capture_output(exercise_code)
        st.code(output, line_numbers=True)
    
    st.markdown("""
    ## Week 2: Reference Material
    
    Please refer to the following links:
    - Library Documentation
        - [Pandas Documentation](https://pandas.pydata.org/docs/)
        - [Numpy Documentation](https://numpy.org/doc/)
        - [Matplotlib Documentation](https://matplotlib.org/stable/users/index.html)
        - [Seaborn Documentation](https://seaborn.pydata.org/index.html)
    - Learning Python
        - [Introduction to Statistical Learning](https://www.statlearning.com/resources-python)
        - [Learning Python notebook](https://github.com/intro-stat-learning/ISLP_labs/blob/stable/Ch02-statlearn-lab.ipynb)
        For our dataset used today for class:
        - [Advertising Dataset](https://www.statlearning.com/s/Advertising.csv)
    """)
    
    # Personalized Weekly Assignment
    username = st.session_state.get("username", "Student")
    st.header(f"{username}'s Weekly Assignment")

    if username == "manxiii":
        st.markdown(f"""
        Hello **{username}**, here is your Assignment 2: Python Basics.
        1. Import the dataset that you studied last week: https://github.com/saralemus7/arthistory
        2. Create a new notebook and load the dataset
        3. Explore the dataset by answering the following questions (submit answers in this [Colab Notebook](https://colab.research.google.com/drive/1ScwSa8WBcOMCloXsTV5TPFoVrcPHXlW2)):
            - How many rows and columns are there in the dataset?
            - What are the variables in the dataset?
            - What is the data type of each variable?
            - What is the range of each variable?
            - What is the mean of each variable?
        4. Think about what research question you want to answer with this dataset.

        **Due Date:** End of Week 2
        """)
    elif username == "zhu":
        st.markdown(f"""
        Hello **{username}**, here is your Assignment 2: Python Basics.
        1. Import the dataset that you studied last week: https://huggingface.co/datasets/zwn22/NC_Crime
        2. Create a new notebook and load the dataset
        3. Explore the dataset by answering the following questions (submit answers in this [Colab Notebook](https://colab.research.google.com/drive/1Q4rgFgPBYyjg0DEQ2ud05shNLNMFDK4l)):
            - How many rows and columns are there in the dataset?
            - What are the variables in the dataset?
            - What is the data type of each variable?
            - What is the range of each variable?
            - What is the mean of each variable?
        4. Think about what research question you want to answer with this dataset.
        """)
    elif username == "WK":
        st.markdown(f"""
        Hello **{username}**, here is your Assignment 2: Python Basics.
        1. Import the dataset that you studied last week: https://huggingface.co/datasets/Yusuf5/OpenCaselist/tree/main
        2. Create a new notebook and load the dataset
        3. Explore the dataset by answering the following questions (submit answers in this [Colab Notebook](https://colab.research.google.com/drive/1LP3R3MrQJ2Mz8ZjPhxgTp9IZAlBE0e1d#scrollTo=e78EtnbQCDKV)):
            - How many rows and columns are there in the dataset?
            - What are the variables in the dataset?
            - What is the data type of each variable?
            - What is the range of each variable?
            - What is the mean of each variable?
        4. Think about what research question you want to answer with this dataset.

        **Due Date:** End of Week 2
        """)
    else:
        st.markdown(f"""
        Hello **{username}**, here is your Assignment 2: Python Basics. is not yet released. Please message instructor
        """)