# 'generic import' of math module
import math
math.sqrt(25)
# import a function
from math import sqrt
sqrt(25) # no longer have to reference the module
# import multiple functions at once
from math import cos, floor
# import all functions in a module (generally discouraged)
from csv import *
# define an alias
import datetime as dt
# show all functions in math module
print(dir(math))
type(2)
type(2.0)
type('two')
type(True)
type(None)
isinstance(2.0, int)
isinstance(2.0, (int, float))
float(2)
int(2.9)
str(2.9)
bool(0)
bool(None)
bool('') # empty string
bool([]) # empty list
bool({}) # empty dictionary
bool(2)
bool('two')
bool([2])
10 + 4
10 - 4
10 * 4
10 ** 4 # exponent
5 % 4 # modulo - computes the remainder
# Python 2: returns 2 (because both types are 'int')
# Python 3: returns 2.5
10 / 4
10 / float(4)
# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)
from __future__ import division
10 / 4 # true division
10 // 4 # floor division
x = 5
x > 3
x >= 3
x != 3
x == 5
5 > 3 and 6 > 3
5 > 3 or 5 < 3
not False
False or not False and True # evaluation order: not, and, or
# if statement
if x > 0:
print('positive')
# if/else statement
if x > 0:
print('positive')
else:
print('zero or negative')
# if/elif/else statement
if x > 0:
print('positive')
elif x == 0:
print('zero')
else:
print('negative')
# single-line if statement (sometimes discouraged)
if x > 0: print('positive')
# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'
'positive' if x > 0 else 'zero or negative'
# create an empty list (two ways)
empty_list = []
empty_list = list()
# create a list
simpsons = ['homer', 'marge', 'bart']
# print element 0
simpsons[0]
len(simpsons)
# append element to end
simpsons.append('lisa')
simpsons
# append multiple elements to end
simpsons.extend(['itchy', 'scratchy'])
simpsons
# insert element at index 0 (shifts everything right)
simpsons.insert(0, 'maggie')
simpsons
# search for first instance and remove it
simpsons.remove('bart')
simpsons
# remove element 0 and return it
simpsons.pop(0)
# remove element 0 (does not return it)
del simpsons[0]
simpsons
# replace element 0
simpsons[0] = 'krusty'
simpsons
# concatenate lists (slower than 'extend' method)
neighbors = simpsons + ['ned', 'rod', 'todd']
neighbors
# counts the number of instances
simpsons.count('lisa')
# returns index of first instance
simpsons.index('itchy')
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
# element 0
weekdays[0]
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
# starting point is implied to be 0
weekdays[:3]
# elements 3 (inclusive) through the end
weekdays[3:]
# last element
weekdays[-1]
# every 2nd element (step by 2)
weekdays[::2]
# backwards (step by -1)
weekdays[::-1]
# alternative method for returning the list backwards
list(reversed(weekdays))
simpsons.sort()
simpsons
# sort in reverse
simpsons.sort(reverse=True)
simpsons
# sort by a key
simpsons.sort(key=len)
simpsons
sorted(simpsons)
sorted(simpsons, reverse=True)
sorted(simpsons, key=len)
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
num
# create a second reference to the same list
same_num = num
# modifies both 'num' and 'same_num'
same_num[0] = 0
print(num)
print(same_num)
# copy a list (two ways)
new_num = num[:]
new_num = list(num)
num is same_num # checks whether they are the same object
num is new_num
num == same_num # checks whether they have the same contents
num == new_num
# create a tuple directly
digits = (0, 1, 'two')
# create a tuple from a list
digits = tuple([0, 1, 'two'])
# trailing comma is required to indicate it's a tuple
zero = (0,)
digits[2]
len(digits)
# counts the number of instances of that value
digits.count(0)
# returns the index of the first instance of that value
digits.index(1)
# elements of a tuple cannot be modified (this would throw an error)
# digits[2] = 2
# concatenate tuples
digits = digits + (3, 4)
digits
# create a single tuple with elements repeated (also works with lists)
(3, 4) * 2
# sort a list of tuples
tens = [(20, 60), (10, 40), (20, 30)]
sorted(tens) # sorts by first element in tuple, then second element
# tuple unpacking
bart = ('male', 10, 'simpson') # create a tuple
(sex, age, surname) = bart # assign three values at once
print(sex)
print(age)
print(surname)
# convert another data type into a string
s = str(42)
s
# create a string directly
s = 'I like you'
s[0]
len(s)
s[:6]
s[7:]
s[-1]
s.lower()
s.upper()
s.startswith('I')
s.endswith('you')
# checks whether every character in the string is a digit
s.isdigit()
# returns index of first occurrence, but doesn't support regex
s.find('like')
# returns -1 since not found
s.find('hate')
# replaces all instances of 'like' with 'love'
s.replace('like', 'love')
# split a string into a list of substrings separated by a delimiter
s.split(' ')
# equivalent (since space is the default delimiter)
s.split()
s2 = 'a, an, the'
s2.split(',')
# join a list of strings into one string using a delimiter
stooges = ['larry', 'curly', 'moe']
' '.join(stooges)
# concatenate strings
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
s5 = ' ham and cheese '
s5.strip()
# old way
'raining %s and %s' % ('cats', 'dogs')
# new way
'raining {} and {}'.format('cats', 'dogs')
# new way (using named arguments)
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')
# use 2 decimal places
'pi is {:.2f}'.format(3.14159)
# normal strings allow for escaped characters
print('first line\nsecond line')
# raw strings treat backslashes as literal characters
print(r'first line\nfirst line')