-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtutorial.qmd
More file actions
311 lines (203 loc) · 9.42 KB
/
tutorial.qmd
File metadata and controls
311 lines (203 loc) · 9.42 KB
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
---
title: ACM Python Programming Event
author: University of Scranton ACM Student Chapter
execute:
eval: false
---
# University of Scranton Association for Computing Machinery Student Chapter Python Programming Event
## Table of Contents
[Prerequisites](#prerequisites)
[The Basics](#the-basics)
[Classes and Objects](#classes-and-objects)
[Libraries](#libraries)
[Compilation vs. Interpretation](#compilation-vs-interpretation)
## Background
Python is an interpreted programming language, meaning that every line of any given file is read and immediately executed, as opposed to being compiled to an intermediate format before execution. It features numerous components of other modern programming languages including dynamic typing, high-level data types, object-orientation, and classes. Its simple syntax and numerous third party libraries are what make the language powerful and versatile.
Duck programming
Dropbox, Instagram, Spotify, and Reddit just to name a few
Many builtins are written in C, which means you can expect C-like performance when you run your code (unless your code is slow)
### Prerequisites
Python is a dynamically typed language that does the thing
If you don't have python, you can download it for your system [here](https://www.python.org/downloads/). Python files are created and saved with the `.py` extension.
We trust you can get it set up on your IDE of choice.
This tutorial and solution files are available in [this GitHub repository](https://github.com/BernardScottIII/acm_python_event).
^^ This should be displayed with GitHub Pages or other free static-website software!
### The Basics
#### Variables and Data Types
Here is an example of primitive types.
Doubles aren't a thing
```{python}
x = 10
_argument_variable = "My Variable"
variable_12345 = False
3lectric_City = 3.14 # <- Invalid!
```
Here are more advanced data types that are built directly into python.
Tuples are cool because of caching!
```{python}
my_list = [10, 20, 30]
my_dictionary = {
"Key 1": "Value 1",
"Key 2": "Value 2",
}
my_tuple = (1.11, 2.22, 3.33)
```
#### Useful Type Conversions
Python can't convert anything to anything, but here's some useful and conveinent conversions Python automatically takes care of
```{python}
```
#### Elementary I/O
format strings (f-strings)
```{python}
print("This is a print statement!")
input("I am asking the user to type something then press enter ")
user_input = input("I save what the user types by assigning it to a variable: ")
print("Doing some calculations...")
print(f"The result of the calcualtions are: {user_input}")
```
#### Running a python program
To run your python file, navigate to the directory the file is stored in, and simply type `python` _`filename`_`.py` and press enter.
#### Flow Control
Flow control examples. Talk about how indentation must be strictly followed here. best practice is to use 4 spaces
```{python}
# Replace with a list
for i in range(10):
print(i)
print("for-loop completed!")
# introduce range, then list(range) then use range in a for loop
# Python can create things which provide things to you in repeated calls
my_control_variable = 15
while my_control_variable > 0:
print(my_control_variable)
my_control_variable -= 1
print("while loop completed")
```
#### Functions
Functions are cool
```{python}
def append_fizz(text: str):
text += "fizz"
return text
first_string = "fizz"
second_string = "buzz"
user_string = input("Call append_fizz() on: ")
print(append_fizz(first_string))
print(append_fizz(second_string))
print(append_fizz(user_string))
```
#### Debugging/Troubleshooting with the terminal
Useful note: you can quickly write and run python code in the terminal/cli by typing "python". After you enter that command, you'll be brought to a python editor completely within the terminal/command line interface!
```{bash}
$ python
>>>print("Hello Scranton!")
Hello Scranton!
>>> ^Z # <- how to exit the editor
$
```
### Classes and Objects
Objects are implemented in a similar fashion to Java, where one would create a class, ideally within its own `.py` file, for a single object. Every class contains a constructor, the `__init__()` function. This function must take the argument `self` to declare and instantiate instance variables. Assignment of instance variables takes place completely within the `__init__()` function. Python does not allow for the declaration of multiple constructors, (insert reasoning). However, you can supply default arguments to the lone constructor, which may or may not be used upon invoking the constructor.
```{python}
# No need to copy! For illustration purposes only.
class MyExampleClass:
def __init__(self):
self.my_instance_variable = 10
self.another_instance_variable = "Instance String"
def example_observer_method(self):
return self.my_instance_variable
```
Create a simple object in a new file named `rectangle.py` and do things with it
```{python}
class Rectangle:
def __init__(self, height, width):
self.height = height
self.width = width
self.perimeter = ( 2 * height ) + ( 2 * width )
self.area = height * width
def get_height(self):
return self.height
def get_width(self):
return self.width
def get_perimeter(self):
# STUB
def get_area(self):
# STUB
```
You can do what you'd typically expect you can do with objects, including passing them to and from functions
```{python}
import math
rectangle_1: Rectangle = Rectangle(3, 4)
rectangle_2: Rectangle = Rectangle(5, 12)
def calc_diagonal(rectangle: Rectangle):
height = # STUB
width = # STUB
return math.sqrt( ( height ** 2 ) + ( width ** 2 ) )
print(calc_diagonal(rectangle_1))
print(calc_diagonal(rectangle_2))
```
It is typical to have multiple files, each with a single object/class so other programmers can read and understand what you wrote
### Libraries
Thanks to the extensive community support, python has a vast suite of libraries which implement all sorts of functionality which allows python to be used in a variety of applications! This community support is one of the main reasons that it has become so popular!
Python libraries can be written in languages other than python, including C, Rust, and C++.
Since many popular libraries are created by third parties, they are not installed automatically with your installation of python. If you installed python from [python.org](https://www.python.org/downloads/), then `pip` (Preffered Installer Program) will be installed with python. `pip` can install packages from `PyPI` (The Python Package Index), where most third-party packages are available.
Mention Anaconda python distro and Conda package manager
To install your first packages, run these two commands in your terminal/cli!
```{bash}
$ pip install requests
$ pip install beautifulsoup4
```
#### `requests` and Beautiful Soup (`bs4`)
These two libraries are essential for getting and displaying data to and from websites.
```{python}
import requests
us_debt_apr = requests.get("https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?fields=record_calendar_year,record_calendar_month,record_calendar_day,tot_pub_debt_out_amt&filter=record_calendar_year:eq:2024,record_calendar_month:eq:04&sort=-record_calendar_day")
print(us_debt_apr)
print(us_debt_apr.json())
print(us_debt_apr.json()["data"])
print(us_debt_apr.json()["data"][0])
print(us_debt_apr.json()["data"][0]["tot_pub_debt_out_amt"])
from bs4 import BeautifulSoup
response = requests.get("https://en.wikipedia.org/wiki/Web_scraping")
print(response.content)
soup = BeautifulSoup(response.content, "html.parser")
print(soup.title)
```
_If you're interested in working with fiscal data from the U.S. Treasury, refer to the API documentation [here](https://fiscaldata.treasury.gov/api-documentation/)._
#### `statistics`
`Standard library, no download necessary!`
The statistics library is very useful for business-oriented applications. It has tremendous functionality including being able to produce a linear regression and covariance.
```{python}
import statistics
# put this data in a csv
# use zip()
us_debt = requests.get("https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?fields=record_calendar_year,record_calendar_month,record_calendar_day,tot_pub_debt_out_amt&sort=-record_calendar_day")
debt_vals = []
for month in us_debt.json()["data"]:
debt_vals.append(float(month["tot_pub_debt_out_amt"]))
print(debt_vals)
print(statistics.mean(debt_vals))
print(statistics.stdev(debt_vals))
```
#### `numpy` and `matplotlib`
```{bash}
$ pip install numpy
$ pip install matplotlib
```
Two libraries essential for research applications. `numpy` provides support for high-order arrays and greatly optimizes large matrix operations. `matplotlib` works well with `numpy` and is used for visual representation of data.
```{python}
import numpy as np
import matplotlib.pyplot as plt
time = np.arange(len(debt_vals))
# print(time)
slope, intercept = np.polyfit(time,debt_vals,1)
# print(slope, intercept)
poly1d_fn = np.poly1d((slope, intercept))
plt.plot(time, debt_vals,'bo',poly1d_fn(time), '--k')
```
### Compilation vs. Interpretation
talk about that here. I know nothing about this
#### Compilation
#### Interpretation
#### Performance
_for performance reasons_
## Wrap-Up
if you want us to continue these sessions, in either the same language or a different language, please let us know in a survey