<jupyter_start><jupyter_text>Python Basics <NAME>, 2021 This Jupyter Notebook accompanies the Data Science lectures for the 2021 UChicago Pathways in Economics program for high school students. In this introductory notebook, students will cover basic topics in Python. This notebook is aimed at students with zero programming background. The topics include:- Variable assignment- Commenting- Importing packages- Calculator functions- Boolean variables- FunctionsThis lecture is designed to be worked through at your own pace. Your TA will be able to assist you with any difficulties you may encounter. **A quick note on the exercises:** The best way to learn Python is by doing. After each topic, I have included short exercises as a helpful tool for learning. They are not supposed to be difficult and usually are fairly similar to the sample code I've written in this notebook. When you get to each exercise click the `plus` sign in the tool bar to create a new cell. Try and solve the exercises right there. There are often many ways to solve a problem and I've included sample solutions at the end of the notebook to compare.These lectures are inspired by the Quantecon Datascience notebooks. https://datascience.quantecon.org/  1. Variable AssignmentVariable assignment associates a value to a variable. We can associate many different kinds of of values. **Click run or type `shift` + `Enter` to execute the cell**<jupyter_code># assign the value `5` to the variable `x`
x = 5
# print out the value associated with `x`
print(x)<jupyter_output>5<jupyter_text>We can also assign words to variables.<jupyter_code>myname = "Alex"
print(myname)<jupyter_output>Alex<jupyter_text>We can write over the variable to assign a new value.<jupyter_code>print(myname)
myname = "<NAME>"
# Run again to see that value has changed
print(myname)<jupyter_output><NAME><jupyter_text>CommentsCode comments are short notes that you leave for future readers of your code (usually yourself). Comments explain what the code does.Be kind to your future self; leave lots of comments.<jupyter_code>firstname = "Lebron"     # Assign the variable firstname
lastname  = "James"      # Assign the variable lastname

# Combine the firstname, a space, and lastname 
name = firstname + " " + lastname

# Print out the full name
print(name)<jupyter_output><NAME><jupyter_text>Exercise 1---Here is an exercise to practice the material we've just learned.I've included **example solutions** at the *end of the notebook*.1. Assign your first name to the variable `firstname`.2. Assign your last name to the variable `lastname`.3. Combine your first name, last name, and a space into on variable `name`.4. Use the function `len` to find out the number of letters in the variable `name`.    - The way you use `len` is similar to the way we used `print`.5. Assign the result of part (4) to a variable named `num_letters`.  2. PackagesPackages are collections of tools bundled together. Some of these libraries are massive projects maintained by many developers online.- `numpy` is a package with many tools for math (esp. linear algebra). - `pandas` is a package for data manipulation and analysis.- `matplotlib` is a library for making plots and data visualization.---Load packages using the function `import`.<jupyter_code># We are importing `numpy` with the nickname `np` for later convinience.
import numpy as np<jupyter_output><empty_output><jupyter_text>Access functions and objects from the package using the following syntax. `package.function`<jupyter_code># We are going to access the function `mean` from the package `numpy`.

list_of_numbers = [1, 2, 3]      # create a list of numbers

avg = np.mean(list_of_numbers)   # compute the mean

print(avg)                       # print out the answer<jupyter_output>2.0<jupyter_text>Exercise 2--- Part A1. Load the package `time` with the nickname `tt`2. Use the function `localtime()` from the `time` package to see what the time is where you are right now.                **Warning** Don't forget the parenthesis after the function name.3. Output should look like below.>time.struct_time(tm_year=2021, tm_mon=2, tm_mday=5, tm_hour=19,  tm_min=41, tm_sec=59, tm_wday=4, tm_yday=36, tm_isdst=0)--- Part B Before we used the function `np.mean()` to compute the average of a list of numbers. Now we will use the function `np.sum()` in order to compute the sum.1. Create a new list of numbers using the numbers 5, 10, and 15.2. Use the function `np.sum()` to compute the sum.  3. Python can function as a calculator<jupyter_code># Assign variables
a = 10
b = 2

print(a)
print(b)
# Lets do some addition
a + b
# Now some subtraction
a - b
# Python can do many kinds of arithmetic
print("a + b is", a + b) # addition
print("a - b is", a - b) # subtraction
print("a * b is", a * b) # multiplication
print("a / b is", a / b) # division
print("a ** b is", a**b) # exponent

print("\nPython follows PEMDAS.\n")

out1 = (a + b) * a
out2 = a + (b * a)

print("out1 = ", out1)
print("out2 = ", out2)<jupyter_output>a + b is 12
a - b is 8
a * b is 20
a / b is 5.0
a ** b is 100

Python follows PEMDAS.

out1 =  120
out2 =  30<jupyter_text>4. FunctionsFunctions take inputs and return outputs. We've already worked with a few functions so far. - `print()`- `np.mean()`- `+`- `-`- `len()`We can write our own functions. Every function starts with `def` and ends with `return`.<jupyter_code>def add2(input_number):
    '''This is a simple function that adds 2 to any input.'''
    result = input_number + 2
    return result
ans = add2(21)
print(ans)<jupyter_output>23<jupyter_text>Exercise 41. Write a new function called `minus6`. 2. Similar to the function we wrote above it takes x as an input and returns x-6  5. ListsLists are a collections of items. Each item can be of any type. We have already worked with a list of numbers previously.<jupyter_code>mylist = [5, "Alex", 6.3]
print(mylist)<jupyter_output>[5, 'Alex', 6.3]<jupyter_text>Access items in a list using brackets.This is called indexing.- Python starts counting at zero.<jupyter_code>mylist[0] # first element
print(mylist[1]) # second element
print(mylist[2]) # third element<jupyter_output>6.3<jupyter_text>Use the function `len()` to compute the number of elements there are in a list.<jupyter_code>num_elements = len(mylist)
print(num_elements)<jupyter_output>3<jupyter_text>Exercise 5---We are going to double check that the `np.mean()` function is working correctly.1. Make a list, named `list1`, with the numbers 1, 4, 7, 10, and 200.2. Use `np.sum()` to compute the sum of `list1`, name that `listsum1`.3. Get the number of elements in `list1`, name that `numelements1`.4. Compute the average of `list1` as follows: (Recall: / means divide in python.)$$mymean1 = \frac{listsum1}{numelements1}$$5. Use the `np.mean()` function to compute the mean of `list1`. Call that `numpy_mean`.6. Check the answers are identical.  6. For LoopsFor loops will loop over a list and do an operation for each element.  Lets make a list named `basket`.<jupyter_code>basket = ['apple', 'banana', 'grapes']
print(basket)
# For each element in our basket
# we're going to print out the phrase "Eat ____"
# We will remove the fruit from our basket

for item in basket:
    print('Eat ', item)<jupyter_output>Eat  apple
Eat  banana
Eat  grapes<jupyter_text>For loops are also helpful for working with a list of numbers.<jupyter_code>for ii in [1,2,3,4,5]:
    isquared = ii ** 2    
    print('The squared number = ', isquared)<jupyter_output>The squared number =  1
The squared number =  4
The squared number =  9
The squared number =  16
The squared number =  25<jupyter_text>Quiz 6---We are going to double check the function `np.sum()` works correctly.1. Create a variable named tally = 0.2. Create `list2` $=[1000,2000,3000]$.3. Use a for loop to compute the sum of `list2`.    - Hint: Use the for loop to add each element to the tally.4. Compare to `np.sum()`.  7. BooleansThere are different kinds of variables. So far we've worked with- **strings** (words)- **floats** (numbers with decimals)- **integers** (numbers without decimals)Now we're going to work with Boolean variables. A boolean variable is either true or false.<jupyter_code>x = True
y = False

print(x)
print(type(x))
a = 10
b = 16

print(a > b)
print(a < b)
print("a = ", a)
print("b = ", b)
print("a > b", "is", a > b)   # greater than
print("a < b", "is", a < b)   # less than 
print("a == b", "is", a == b) # check for equality
print("a >= b", "is", a >= b) # greater than or equal to
print("a <= b", "is", a <= b) # less than or equal to<jupyter_output>a =  10
b =  16
a > b is False
a < b is True
a == b is False
a >= b is False
a <= b is True<jupyter_text>Booleans variables are the output of **variable comparison**. **Multiple comparisons** are handy.<jupyter_code>a = 4
b = 5

(a < b ) and (a < 2*b) # true if both are true, and false if at least one is false<jupyter_output><empty_output><jupyter_text>SolutionsCongrats! You've completed this intro notebook.  Example Answers 1<jupyter_code>num_letter = len(myname)
print(num_letter)<jupyter_output>12<jupyter_text>Example Answers 2<jupyter_code># Part A
import time as tt

time_right_now = tt.localtime()
print(time_right_now)
# Part B

new_list_of_numbers = [5,10,15]

print("Sum of these numbers is = ")

np.sum(new_list_of_numbers)<jupyter_output>Sum of these numbers is =<jupyter_text>Example Answers 4<jupyter_code>def minus6(x):
    '''This is a simple function subtracts 6 from x.'''
    result = x - 6
    return result
ans = minus6(21)
print(ans)<jupyter_output>15<jupyter_text>Example answers 5<jupyter_code># 1. Make a list
list1 = [1, 4, 7, 10, 200]

#2. Compute the sum of the list
listsum1 = np.sum(list1)

# 3. Get the number of elements in list1
numelements1 = len(list1)

# 4. Compute average manually
mymean1 = listsum1 / numelements1

# 5. Numpy average
numpy_mean = np.mean(list1)

# 6. Compare
print("My mean = ", mymean1)
print("Numpy mean = ", numpy_mean)<jupyter_output>My mean =  44.4
Numpy mean =  44.4<jupyter_text>Example answers 6<jupyter_code>list2 = [1000, 2000, 3000]

numpy_sum = np.sum(list2)
print('Numpy sum = ', numpy_sum)
tally = 0

for num in list2:
    # Add current num to the tally
    tally = tally + num
    
print('My sum = ', tally)<jupyter_output>My sum =  6000
{'fraction_non_alphanumeric': 0.1003883495145631, 'fraction_numerical': 0.024077669902912623, 'mean_word_length': 4.351168831168831, 'pattern_counts': {'":': 0, '<': 76, '<?xml version=': 0, '>': 75, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '20', 'dir': 'jupyter-structured-clean-dedup', 'id': '655027', 'license': 'MIT', 'n_tokens_mistral': 3471, 'n_tokens_neox': 3249, 'n_words': 1390, 'path': 'files/bigdata_pythonbasics.ipynb', 'repo_name': 'Alexander-Weinberg/Alexander-Weinberg.github.io', 'size': '10330'}