Intro to Python

UofT Coders, Jan 10 2019

Author: Ahmed Hasan, borrowing heavily from Madeleine Bonsma-Fisher, Lina Tran, Charles Zhu, and Amanda Easson


The interpreter

Math with integers


In [ ]:
2 + 2

In [ ]:
2 * 3

In [ ]:
2 ** 3

In [ ]:
# % is the modulus operator
# x % y -> return the remainder of x / y
2 % 3

Math with floats

Floats = floating point numbers


In [ ]:
2.0 * 3

In [ ]:
2.5 * 3

In [ ]:
2 * 3;

Variables


In [ ]:
year = 2019
name = 'Ahmed' # this is a string

In [ ]:
print(year)

print(name)

In [ ]:
print(type(name))

In [ ]:
print(type(2.0))

In [ ]:
print(type(year))

In [ ]:
# how exactly does print work again?

help(print)

Lists


In [ ]:
# lists - square brackets!

fruits = ['apple', 'orange', 'mango']

In [ ]:
print(fruits)
print(type(fruits))

In [ ]:
misc = [42, 'python!', 2.57]
print(misc)

In [ ]:
# concatenating lists
fruits + fruits

Indexing lists and strings


In [ ]:
# indexing in python begins at 0! 

print(fruits[0])
print(type(fruits[0]))

In [ ]:
# slicing multiple things
# start : end (exclusive!)

# recall that fruits = ['apple', 'orange', 'mango']

print(fruits[0:2])
print(fruits[0:])
print(fruits[:3])

print(fruits[-1]) # last item of a list
print(fruits[-2])

In [ ]:
# reassigning item in list
fruits[2] = 'banana'
print(fruits)

In [ ]:
# slicing and indexing strings

my_string = 'This is a string.'

print(my_string[1:])

In [ ]:
# strings do not support reassignment
# try running this: my_string[0] = 't'

Dictionaries


In [ ]:
# dictionaries allow us to store key value pairs

fruit_colors = {'banana': 'yellow',
                'apple': 'red',
                'orange': 'orange'}

In [ ]:
# keys are 'looked up' using square brackets

print(fruit_colors['banana'])

In [ ]:
# additional keys can be added after the fact
fruit_colors['lemon'] = 'yellow'
print(fruit_colors)

If statements


In [ ]:
# python can check whether certain statements are true or false

2 > 1

In [ ]:
# use == to test for equality
1 == 1

In [ ]:
x = 5
isinstance(x, int)

In [ ]:
# with these expressions, we can construct if statements
# if statements allow our scripts to encode more complex instructions

x = 5
if isinstance(x, int):
    print(x, 'is an integer')

In [ ]:
# if-else

if isinstance(x, str):
    print(x, 'is a string')
else:
    print(x, 'is not a string')

In [ ]:
# if-elif-else
# useful if we have multiple conditions to test

if isinstance(x, str):
    print(x, 'is a string')
elif isinstance(x, int):
    print(x, 'is an integer')
else:
    print(x, 'is neither a string nor an integer')

For loops


In [ ]:
# for loops allow us to automate repetitive operations

# how do we check which values in this list are even?
nums = [1, 2, 3, 4]

# could check them individually?
print(nums[0] % 2)
print(nums[1] % 2)

In [ ]:
# for loops simplify this
# here, 'number' is a placeholder variable for each of the items in the list

for number in nums:
    if number % 2 == 0:
        print(number, 'is even')

In [ ]:
# we can also loop over the contents of a string
vowels = 'aeiou'
for letter in vowels:
    print(letter)

Functions


In [ ]:
# functions allow us to generalize operations
# what is the sum of squares of two numbers?

x = 5
y = 7

print((x ** 2) + (y ** 2))

In [ ]:
def sum_of_squares(num1, num2):
    ''' (int, int) -> int
    input: two integers
    output: the sum of the squares of the two numbers
    '''
    ss_out = num1 ** 2 + num2 ** 2
    return ss_out

# def is the keyword to define functions
# each function typically ends with a return statement

In [ ]:
output = sum_of_squares(x, y)
print(output) # our operation from above
print(sum_of_squares(50, 42)) # works with any values we want!

In [ ]:
# checking on our docstring
help(sum_of_squares)

Some useful packages


In [ ]:
# use a package by importing it
# these can be given a shorter alias

import numpy as np

In [ ]:
# packages provide all sorts of useful functionality
# numpy allows for efficient numerical calculations in python

np_array = np.arange(15)
list_array = list(range(15))

print(np_array)
print(type(np_array))
print(list_array)
print(type(list_array))

In [ ]:
# numpy arrays also allow for vectorized operations

print(np_array * 2)
print(list_array * 2)

In [ ]:
# numpy arrays also have helpful 'methods'
# a method is a special function 'attached' to an object, to be used on the object itself

# what's the mean of our array?
print(np_array.mean())

In [ ]:
# the max value in our array?
print(np_array.max())

In [ ]:
import pandas as pd
import seaborn as sns # we will use this for plotting
%matplotlib inline
iris = sns.load_dataset('iris')

In [ ]:
iris.head()

In [ ]:
iris.columns

In [ ]:
# pull out specific rows with the .loc method
iris.loc[0:2]

In [ ]:
# or rows AND columns
# use a list for multiple columns!

iris.loc[0:2, 'petal_length']

In [ ]:
iris.loc[0:2, ['petal_length', 'species']]

In [ ]:
sns.relplot(x='petal_length', y='petal_width', data=iris)

In [ ]:
sns.relplot(x='petal_length', y='petal_width', hue='species', data=iris)