Template [Python]

This repo is mounted by: Python

1. Data types, data structures and indexing

1.1 Basics

Object, assignment, functions, how to comment and get help

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python
# We can use Python as a calculator!
Shift+Enter to run
Python
# Built-in functions can help execute things; we usually have to provide arguments
Shift+Enter to run
Python
# Don't know how a function works? Ask for help!
Shift+Enter to run
Python

1.2 Data types

Numeric: integer and float

0.1s
Python
Shift+Enter to run
Python

String

Shift+Enter to run
Python

Boolean

Shift+Enter to run
Python

Not sure?

Shift+Enter to run
Python

1.3 Collections

Lists

Lists are ordered collections of changeable elements

Shift+Enter to run
Python

Can we add element to a list?

Shift+Enter to run
Python

List inception: list of lists

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python

Dictionary

Dictionaries are unordered collections of changeable and indexed elements

Shift+Enter to run
Python
# Dictionairies are made of keys...
Shift+Enter to run
Python
# ... and values
Shift+Enter to run
Python

DataFrame

DataFrames are data structures containing labeled axes

# DataFrame are not a built-in type of Python; we must import an Python library to use them
Shift+Enter to run
Python

Data frames

data.frame(vector1, vector2)	# bind vectors with the same length
# Df can be build from a list of lists
Shift+Enter to run
Python
# Df can be build from dictionary
Shift+Enter to run
Python

1.4 Dimensions

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python

1.5 Indexing

Accessing elements of a list

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python

Looking up values for a specific key

Shift+Enter to run
Python

Getting an entire column of a DF

Shift+Enter to run
Python

Int and Label indexing of DF

# integer indexing [row, col]
Shift+Enter to run
Python
# label indexing [row, col]
Shift+Enter to run
Python

1.6 Slicing

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python
### PRO TIP
# Select rows with capital letters only
Shift+Enter to run
Python

2. Files

Absolute paths

C:/Users/RonBumblefootThal/Documents/pythonFolder/MyFirstProject/Draft/IDon'tKnowWhatI'mDoing/etc.py

Relative Paths

~/I_love_my_project/CoolCode.py

2.1 Working directories

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python

2.2 Save/write files

DF example

soa_tour = pd.DataFrame()
soa_tour['country'] = ['USA', 'UK', 'FRA', 'GER', 'BRA']
soa_tour['frequency'] = [39, 6, 6, 5, 3]
soa_tour['continents'] = ['north_america', 'europe', 'europe', 'europe', 'south_america']
soa_tour
Shift+Enter to run
Python
# df_name.to_csv(PATH, header=BOOL)
Shift+Enter to run
Python
Shift+Enter to run
Python

2.3 Load/read files

From your PC

Shift+Enter to run
Python
Shift+Enter to run
Python
Shift+Enter to run
Python

From URL

Metabolic rates data: http://sciencecomputing.io/data/metabolicrates.csv

url = "http://sciencecomputing.io/data/metabolicrates.csv"
Shift+Enter to run
Python
Shift+Enter to run
Python

Play around a little bit with this big DF... what can you do?

Shift+Enter to run
Python

3. Control Flow

You already apply control flow when you decide how to go to work during winter.

For example:

  • You take the metro if it's snowy

  • You take the metro if it's cold

  • You walk every other time

Let's code it now ;)

3.1 Conditional evaluation

Simple if statement

Structure:

if condition :
	do something

Example:

Shift+Enter to run
Python
Shift+Enter to run
Python

If/else statement

Structure:

if condition1 :
	do something
  
elif condition2 :
	do another thing
  
else :
	do something else

Example:

Shift+Enter to run
Python

Nested statement

if condition1 :
	do something
  
else :
	if conditionA :
  	do another thing
  else :
  	do something else

Example:

Shift+Enter to run
Python
Shift+Enter to run
Python

Multiple conditions: AND & OR

Shift+Enter to run
Python

3.2 For loops

Using a for loop you could plan your outings for a few days based on the forecast

What we are now familiar with:

Shift+Enter to run
Python

What if we want to take into account the forecast for the next five days?

Shift+Enter to run
Python

Can we still use our for loop?

Shift+Enter to run
Python

Iterations

Structure:

for i in [] :
	do something for each i

Examples

Shift+Enter to run
Python
# remember the len function? and how to access elements of a list?
Shift+Enter to run
Python

If statement inside for loop

Structure:

for i in [] :
	if condition on i :
  	do something
  else :
  	do something else

Example:

# don't forget to correctly INDENT
Shift+Enter to run
Python

3.3 Extras

Some logical operators

print (2 < 3)
print (2 > 3)
print (2 <= 2, 1 <= 2)
print (4 >= 4, 4 >= 3)
print (1 == 1)
print (1 != 1, 1 != 2)
0.4s
Python
print (not True, not False)
print (True or False, True | False)
print (True and False, True and True, False & True, False & False)
0.4s
Python

4. Functions

4.1 Syntax and arguments

Basic syntax

def function_name(args) :
	result = do something with args
  
  return result
# name and arguments
# what the function does
# what the function returns
Shift+Enter to run
Python
# apply function on values
Shift+Enter to run
Python
# apply function on variables
Shift+Enter to run
Python

Using built-in functions

Shift+Enter to run
Python
Shift+Enter to run
Python

4.2 Scope

Variables can exist in a global or a local scope.

Remember, the abs_temp_difference function is returning the value of the abs_result variable

# what will 'abs_result' return?
Shift+Enter to run
Python

Here is a second example:

# global variables
Shift+Enter to run
Python
Shift+Enter to run
Python
# global and local variables returned: what is what?
Shift+Enter to run
Python
# which variable does not exist in the global scope?
0.3s
Python
# what is the value of 'squirrels'?
Shift+Enter to run
Python

4.3 Integration

Combining functions and control flow

Let's go back to our forecast example.

Here's the forecast for an entire week:

# week forecast
weather_week = ['snowing', 'cloudy', 'snowing', 'clear', 'rainy']
temp_week = [-15, 3, -2, -23, 11]
# weekend forecast
weather_weekend = ['snowing', 'rainy']
temp_weekend = [-3, 2]
Shift+Enter to run
Python

Let's build a function that will analyze either the week or the weekend forecast

def choose_transporation(weather, temperature) :
	for each day :
  	if snowing or cold :
    	'Take the metro'
    else :
    	'Walk'
Shift+Enter to run
Python
# week transportation
Shift+Enter to run
Python
# weekend transportation
Shift+Enter to run
Python

4.4 Exercise: Animal Metabolism

This exercise will help you integrate the following:

  • Files handling

  • Control flow

  • Function

Write a function to read a file if it exists and downloading it if it does not exist

# Pseudocode
function get_data(fn, url)
	if fn exist
  	open it
    
  else 
  	download from url
# remember the os librairy...
path = 'data/clean/'
fn1 = 'soa_tour_python.csv'
fn2 = 'this_file_does_not_exist.csv'
print (os.path.isfile(path+fn1))
print (os.path.isfile(path+fn2))
0.2s
Python
Shift+Enter to run
Python
filename = 'metabolic_rates.csv'
url = "http://sciencecomputing.io/data/metabolicrates.csv"
Shift+Enter to run
Python
Shift+Enter to run
Python

Extras

Default values

# Define function
Shift+Enter to run
Python
Shift+Enter to run
Python

Runtimes (1)