Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add: presentation slides for activity 1 #84

Merged
merged 2 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 20 additions & 18 deletions clean-modular-code/activity-1/clean-code-activity-1.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ kernelspec:
name: python3
---

+++ {"editable": true, "slideshow": {"slide_type": ""}}

(clean-code-activity-1)=
# Clean, Modular Code: Activity 1

Writing clean, modular code takes practice but is a habit worth building. Over time as you incorporate clean code strategies that improve code quality and maintainability, these strategies will become second nature. Writing cleaner code will make your code easier to read, maintain, and share with others. It will also make your work easier for others (and your future self) to use.

In this exercise, you'll focus on using three key clean code strategies:

1. **Use expressive names**: Assign meaningful names to all variables and functions to make your code more readable. [Learn more about expressive names.](../python-expressive-code.md)
2. **Use a Python style guide (PEP8) for consistent syntax**: Adhere to [PEP8 Python code style rules](../python-pep-8.md), including proper spacing and naming conventions, to maintain a consistent and readable codebase.
3. **Identify opportunities to make your code DRY (Don't Repeat Yourself)**: In this activity, you will use pseudocode to identify areas where the code can be simplified and made DRY. In the next activity, you will implement DRY best practices using loops and functions.
1. [**Use expressive names**](../python-expressive-code): Assign meaningful names to all variables and functions to make your code more readable.
2. [**Use a Python style guide (PEP8) for consistent syntax**](../python-pep-8): Adhere to PEP8 Python code style rules, including proper spacing and naming conventions, to maintain a consistent and readable codebase.
3. **Identify opportunities to [make your code DRY (Don't Repeat Yourself)](../python-dry-modular-code)**: In this activity, you will use pseudocode to identify areas where the code can be simplified and made DRY. In the next activity, you will implement DRY best practices using loops and functions.

By practicing these strategies, you are well on your way to writing clean, efficient, and maintainable code.

Expand Down Expand Up @@ -72,7 +74,7 @@ Examine the code below and address the following questions and statements.
1. Create a list of any issues that you see with the code.
2. Write down: what is the code supposed to do?
3. Does the code run?
4. Work with your partner to create a list of improvements that will make your code more efficient and easier to understand.
4. Work with your partner to create a list of improvements to make your code more efficient and easier to understand.
:::

```{code-cell} ipython3
Expand All @@ -88,25 +90,25 @@ from glob import glob
from pathlib import Path
import numpy as np

path = "data/part-1-data.json"
path="data/part-1-data.json"

with open(path, "r") as z:
x = json.load(z)
with open(path,"r") as z:
x=json.load(z)

import pandas as pd
a=pd.json_normalize(x)

b=['publisher', 'DOI', 'type', 'author','is-referenced-by-count', 'title', 'published.date-parts']
b=['publisher','DOI','type','author','is-referenced-by-count','title', 'published.date-parts']
df=a.filter(items=b)

for i,r in df.iterrows():
l = r["published.date-parts"][0]
df.at[i, 'title'] = df.at[i, 'title'][0]
s = f"{l[0]}-{l[1]:02d}-{l[2]:02d}"
d = pd.to_datetime(s, format='%Y-%m-%d')
df.at[i, 'published_date'] = d
l=r["published.date-parts"][0]
df.at[i, 'title']=df.at[i, 'title'][0]
s=f"{l[0]}-{l[1]:02d}-{l[2]:02d}"
d=pd.to_datetime(s, format='%Y-%m-%d')
df.at[i, 'published_date']=d

df.drop("published.date-parts", axis=1, inplace=True)
df.drop("published.date-parts",axis=1,inplace=True)
print(df.shape)

path="data/part-1-datab.json"
Expand All @@ -115,18 +117,18 @@ with open(path, "r") as z:
x=json.load(z)

a=pd.json_normalize(x)
b=['publisher', 'DOI', 'type', 'author','is-referenced-by-count', 'title', 'published.date-parts']
b=['publisher','DOI','type','author','is-referenced-by-count','title','published.date-parts']
df2=a.filter(items=b)

for i, r in df2.iterrows():
for i,r in df2.iterrows():
l=r["published.date-parts"][0]
df2.at[i, 'title'] = df.at[i, 'title'][0]
s=f"{l[0]}-{l[1]:02d}-{l[2]:02d}"
d=pd.to_datetime(s, format='%Y-%m-%d')
df2.at[i, 'published_date']=d

df2.drop("published.date-parts", axis=1, inplace=True)
df_combined = pd.concat([df, df2], axis=0)
df2.drop("published.date-parts",axis=1,inplace=True)
df_combined = pd.concat([df,df2],axis=0)
df_combined.shape
```

Expand Down
2 changes: 1 addition & 1 deletion clean-modular-code/activity-2/clean-code-activity-2.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ kernelspec:
+++ {"editable": true, "slideshow": {"slide_type": ""}}

(activity-2)=
# Activity 2 - DRY Code & Functions
# DRY Code & Functions: Activity 2

In [activity 1](../activity-1/clean-code-activity-1), you took some code and made it cleaner and easier to understand by:

Expand Down
2 changes: 1 addition & 1 deletion clean-modular-code/activity-3/clean-code-activity-3.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ kernelspec:
+++ {"editable": true, "slideshow": {"slide_type": ""}}

(clean-code-activity-3)=
# Activity 3: Tests & Checks for your code
# Tests & Checks for your code: Activity 3

* In [activity 1](../activity-1/clean-code-activity-1), you made your code cleaner and more usable using [expressive variable names](python-expressive-code) and docstrings to document the module.
* In [activity 2](../activity-2/clean-code-activity-2), you made your code more DRY ("Don't Repeat Yourself") using [functions](write-functions) and [conditionals](conditionals).
Expand Down
169 changes: 169 additions & 0 deletions clean-modular-code/clean-code-present.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
---
jupytext:
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.16.4
kernelspec:
display_name: Python 3 (ipykernel)
language: python
name: python3
---

+++ {"editable": true, "slideshow": {"slide_type": ""}}

# Clean, Modular Code

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

## Part 1: 3 strategies

* Use consistent code format
* Use expressive object names
* Make your code DRY

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

### PEP 8 & consistent code format

* Generally accepted rules for code format: PEP 8
* Code Formatters: Tools to apply PEP 8 as you work!

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: slide
---
#this code is not PEP8 compliant -- why?
def doStuff(a,b):print("Result:",a+b);return(a+b)
x = True
if(x):print("Messy code.");print("Oops!")
```

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: ''
---
# This code is PEP8 compliant -- why?
def do_stuff(number1, number2):
print("Result:", number1 + number2)
return number1 + number2

x = True
if x:
print("This is nicer code.")
print("Yay!")
```

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

#### Code format tools

* Jupyter code formatter (installed in this binder).
* Black
* Ruff

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

#### [Other tools to consider](tools-code-style)

* pre-commit hooks: if you use version control, they run when you commit changes
* setup VSCode (and other IDE's) to format on save®

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

## Expressive code

* Code can become documentation when written well.
* Use variable, function & class names that tell a user what each thing does

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

:::{figure} /images/clean-code/clean-code-expressive-variable-names-basmati-rice.png
:alt: "Image showing a large see-through Tupperware container with cookies in it but a label that says Basmati Rice."

This container clearly contains cookies, yet it's labeled "rice." This might be confusing to someone who is looking for rice in your kitchen! Consider this when writing code. It's easier for someone to understand your code without running it when your code variables describe the objects they contain. Source: Jenny Bryan, Reproducible Science Curriculum.
:::

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: slide
---
# This code is PEP8 compliant -- why?
def do_stuff(number1, number2):
print("Result:", number1 + number2)
return number1 + number2

x = True
if x:
print("This is nicer code.")
print("Yay!")
```

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: ''
---
# This code is PEP8 compliant -- why?
def calculate_sum(number1, number2):
print("Result:", number1 + number2)
return number1 + number2

is_valid = True
if is_valid:
print("This is nicer code.")
print("Yay!")
```

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

## DRY code

* Don't Repeat Yourself
* use functions, loops and conditionals instead

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: slide
---
a = 5
b = 10
print(a + 2)
print(b + 2)
print(a * 2)
print(b * 2)
```

```{code-cell} ipython3
---
editable: true
slideshow:
slide_type: ''
---
def process_number(x):
print(x + 2)
print(x * 2)

numbers = [5, 10]
for num in numbers:
process_number(num)
```

+++ {"editable": true, "slideshow": {"slide_type": "slide"}}

:::{admonition} Begin Activity One!
:class: tip
You are now familiar with 3 strategies for writing better, cleaner code. In the [first activity](clean-code-activity-1), you will apply these principles to example code.

Remember that this is not a test! Rather, it's a chance to think about how you write code and how others may receive it!
:::
1 change: 1 addition & 0 deletions clean-modular-code/intro-clean-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Write Pseudocode <write-pseudocode>
:caption: Activities
:maxdepth: 2

Activity overview <clean-code-present>
Clean Code: Activity 1 <activity-1/clean-code-activity-1>
Clean Code: Activity 2 <activity-2/clean-code-activity-2>
Clean Code: Activity 3 <activity-3/clean-code-activity-3>
Expand Down
1 change: 1 addition & 0 deletions clean-modular-code/python-pep-8.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ df

+++ {"editable": true, "slideshow": {"slide_type": ""}}

(tools-code-style)=
## Tools for Consistent Code Style

It may seem overwhelming to remember hundreds of different rules from style guides like [PEP 8](https://peps.python.org/pep-0008/), [pydocstyle](https://pypi.org/project/pydocstyle/), and others --- the good news is that you don't have to!
Expand Down