Welcome to the HODP Python Bootcamp for Beginners
We assume no prior programming knowledge and give a brief introduction to Python, one of the most widely used programming languages. Python is incredibly useful for doing data analysis, especially for large data sets.
This bootcamp will make sure that you are comfortable with basic Python and equip you with the tools to Google and Stack Overflow your way through more projects!
Shortcuts and Commands
Some useful shortcuts are:
Esc
& Enter
keys are used to toggle between selecting a cell versus editing a cell. Up and down arrows are used to toggle between cells.
Shift + Enter
runs your selected cell and moves to the next cell.
Ctrl / Cmd Enter
runs your current cell.
Ctrl / Cmd + M
lets you change a block of code into text.
Ctrl / Cmd + Y
lets you change a block of text into code.
Ctrl / Cmd + A
lets you insert a block of code above the current one.
Ctrl / Cmd + B
lets you insert a block of code below the current one.
Variables & Operations
A variable is a way to represent data in Python. We declare a variable by giving it a name and a value. Values of the variable can change and can have different types (e.g. integers or strings).
Here is an example of declaring a variable:
y = 3.45
Here we have a variable y
and have assigned it the value 3.45
. Variable names must begin with letters.
To print the value of a variable, we pass the variable to a function called print
.
print(y)
There are four types of values:
Additionally, you can use multiple operations on variables.
For operations on integers, doubles, and floats (e.g. the numbers),
To change the type of a variable, we have int(), str(), bool(), float()
Strings
Strings is the data type that is essentially text. They are treated as an array, or list, of individual characters.
To declare a string, you must use single or double quotation marks
my_str = 'Wow what a string.'
my_other_str = "Wow another string."
However, notice that you cannot add in a line break otherwise an error occurs. To write a multi-line string, you use triple quotation marks, e.g.
my_long_str = """
This string
takes up
many lines.
"""
We will cover some simple operations with strings, including concatenation and parsing, but for more information, see here.
Exercise 1
- Define a variable
x
with value"2"
(that is the string"2"
) - Define a variable
s = "The square of 2.0 is 4.0."
, without typing any numbers and only usingx
. (Hint: Usefloat(), str()
to convert between types.) - Print
s
in all lower case, and then all upper case. - Print the length of
s
. (Hint: This should return25
)
Lists and List Methods
Lists are an easy and flexible way to store different types of information. Since lists are ordered, they can also be accessed via index (e.g. the first item of the list being at index 0
).
To declare a list, use brackets [ ]
to enclose the list and commas ,
to separate each item.
my_list = ["a string", 2, 1.5, True]
Notice how a single list can contain multiple data types.
To declare an empty list,
empty_v1 = []
empty_v2 = list()
The list()
function creates an empty list, but also turns the input into a list.
Here, we will cover some basic info about lists and common list operations.
Exercise 2
- Define a variable
lst
which contains the strings"h", "a", "r", "v", "a", "r", "d"
, in that order. (Hint: Use the functionlist(x)
which takes an iterablex
and returnsx
as a list) - Print out the third letter in the list.
(Hint: This should be
"r"
) - Print the index of the first
"a"
in the list. (Hint: Useindex()
) - Print the number of letters between the first and second
"a"
in the list. (Hint: Uselst[a:b]
to only look at a sublist oflst
, andindex()
) - Append the list
['c', 'o', 'l', 'l', 'e', 'g', 'e','s']
to the end oflst
, and setlst
to be equal to this new list. - Remove the last element from the list (the character
's'
) and print out your lst.
Dictionaries
Dictionaries are like named lists, in that they are mutable and can hold values. However, unlike lists, they attach a key, as opposed to an index, to each value. These key-value pairs make up the dictionary. Values can be any data-type (e.g. strings, ints, lists, dictionaries, etc) while keys must be unique and immutable (e.g. strings, ints, etc. but not lists).
An example of a declaration of a dictionary is:
grades = {"freshman": 9, "sophomore": 10, "junior": 11, "senior": 12}
where to get the value 9
, we would access it with the key:
grades["freshman"]
We'll explore more dictionary functions below.
Some useful functions include
Exercise 3
Create a dictionary
words
with keys"armadillo","armor","arm"
whose values are the number of letters in each of the keys / words.Print out the entire dictionary.
Print the number of keys in
words
.Print out the value associated with the key
"armadillo"
.
Conditionals
Conditionals are if
statements, which takes some boolean expression (e.g. an expression that evaluates to true or false) and "if" True
, performs an action.
More concisely, in Python syntax, it is:
if (...):
# do something
elif (...):
# do something else
else:
# do something else
We'll touch on the elif
and else
more below.
But what about when x
is not equal to y
? Below, we have a more comprehensive if
statement using elif
(short for "else if") and else
.
Exercise 4
- Define a variable
age
as an integer with value65
. - Write a conditional statement which prints
"You are old."
ifage
is greater than or equal to30
,"You are not old."
ifage
is between13
and30
, and"Child."
ifage
is less than or equal to13
. - Change
age
to have value20
, and then10
and see if what you expected to happen occurs!
For Loops
In Python, whenever you want to iterate over a list, dictionary, string, etc. (any iterable), you can use for loops to perform an action on each element of the iterable.
An example of a for loop would be, if I had some list named students
,
for student in students:
# do something
where I chose student
to refer to each element of the list students
(but any valid variable name would have worked as well).
Below, we will delve into more examples of for loops.
One useful function is enumerate
, which essentially pairs each element with an index.
Another very useful (and common) function is range
, which returns a sequence of numbers.
Exercise 5
- Define a variable
nums
as a list of every number from 0 to 19 (inclusive). (Hint: Userange
.) - Define a new variable
squares
as the list of every number innums
squared (e.g.[0,1,4,...,361]
). - Print out the sum of all the elements in
squares
. (*Hint: Should evaluate to2470
).
Functions
Oftentimes, we will want to perform the same action (with the same chunk of code) in multiple areas. To avoid copy & pasting everything multiple times, we define functions. Functions can take in inputs and return an output.
The syntax for defining a function is:
def square(x):
return x**2
where square(x)
takes in a variable and returns the value squared. To call this function, we can run
square(2)
which would then return 4
. Notice how it is not actually another variable or x
. This is because x
is just what the function internally calls the input, and is not necessarily the name of the input outside of the function definition.
Below, we will go through a couple more examples of functions.
Now, what happens when the input, lets call it x
, is both defined outside the function and inside the function?
Exercise 6
Define a function
long(s)
which takes in a strings
and prints the string"long"
if the length ofs
is greater than10
. Else, it prints"not long"
. Print the result oflong("word")
andlong("universities")
.Define a funcion
multiple(k, n)
which takes in an intn
and returns a list of all multiples ofk
less than or equal ton
. Print the result ofmultiple(3,9)
andmultiple(3,3)
.
Imports
Oftentimes, there are functions that people want to use for different projects and don't want to copy over or rewrite the same function multiple times. This is where imports come in.
Python has an incredibly large amount of available libraries for doing almost anything you could possibly need, from making graphs, to analyzing data, to even implementing neural networks.
To access these libraries we use imports. For example, some common libraries for data analysis are Numpy and Pandas. Thus, to use these libraries, you would
import numpy as np
import pandas as pd
where we have imported the libraries Numpy and Pandas, and gave them a "nickname" so that we don't have to type the entire word each time we call on a function from the library.
To use functions from these libraries, e.g. Numpy's array
function, which takes in a list and returns an ndarray
(Numpy's own array), I would
lst = [1,2,3,4,5]
lst = np.array(lst)
If I do not want to type the np.array
each time I call the function, or only want to import that function and not the whole library, I can specify that I just want to import array
, e.g.:
from numpy import array
and then I can just type array()
each time I call the function.
Practice Problems
Problem 1
Define a function place(lst, i, n)
which takes in a list of ints lst
and inserts at index i
all numbers from 0
up to (but not including) n
. This should edit the list lst
in place and not return anything.
For example,
lst = [-2,-1,5]
place(lst, 2, 5)
print(lst)
should print out
[-2,-1,0,1,2,3,4,5]
as we insert numbers 0
through 4
starting at index i
.
Hint: Check out the list operations which has a very handy function insert
.
Problem 2
Define a function fib(x)
which returns the x
th Fibonacci number, with 1,1,2
being the first three Fibonacci numbers.
Then, using the function you just defined, print out a list of the first 20
Fibonacci numbers.
Problem 3
Define a function count_abc(s)
which takes in a string s
and returns the number of times the string "abc#"
where the #
represents any digit. Essentially, we want to know the number of instances of the strings "abc0",...,"abc9"
in s
.
For example,
count_abc("asdabckabc1")
should return 1
, and
count_abc("abbc1abc0abc91")
should return 2
.
Hint: Check out the string function count()
which counts the number of times a substring appears in a string).