In [1]:
# 'generic import' of math module
import math
math.sqrt(25)
Out[1]:
In [2]:
# import a function
from math import sqrt
sqrt(25) # no longer have to reference the module
Out[2]:
In [3]:
# import multiple functions at once
from math import cos, floor
In [4]:
# import all functions in a module (generally discouraged)
from csv import *
In [5]:
# define an alias
import datetime as dt
In [6]:
# show all functions in math module
print(dir(math))
In [7]:
type(2)
Out[7]:
In [8]:
type(2.0)
Out[8]:
In [9]:
type('two')
Out[9]:
In [10]:
type(True)
Out[10]:
In [11]:
type(None)
Out[11]:
In [12]:
isinstance(2.0, int)
Out[12]:
In [13]:
isinstance(2.0, (int, float))
Out[13]:
In [14]:
float(2)
Out[14]:
In [15]:
int(2.9)
Out[15]:
In [16]:
str(2.9)
Out[16]:
In [17]:
bool(0)
Out[17]:
In [18]:
bool(None)
Out[18]:
In [19]:
bool('') # empty string
Out[19]:
In [20]:
bool([]) # empty list
Out[20]:
In [21]:
bool({}) # empty dictionary
Out[21]:
In [22]:
bool(2)
Out[22]:
In [23]:
bool('two')
Out[23]:
In [24]:
bool([2])
Out[24]:
In [25]:
10 + 4
Out[25]:
In [26]:
10 - 4
Out[26]:
In [27]:
10 * 4
Out[27]:
In [28]:
10 ** 4 # exponent
Out[28]:
In [29]:
5 % 4 # modulo - computes the remainder
Out[29]:
In [30]:
# Python 2: returns 2 (because both types are 'int')
# Python 3: returns 2.5
10 / 4
Out[30]:
In [31]:
10 / float(4)
Out[31]:
In [32]:
# force '/' in Python 2 to perform 'true division' (unnecessary in Python 3)
from __future__ import division
In [33]:
10 / 4 # true division
Out[33]:
In [34]:
10 // 4 # floor division
Out[34]:
In [35]:
x = 5
In [36]:
x > 3
Out[36]:
In [37]:
x >= 3
Out[37]:
In [38]:
x != 3
Out[38]:
In [39]:
x == 5
Out[39]:
In [40]:
5 > 3 and 6 > 3
Out[40]:
In [41]:
5 > 3 or 5 < 3
Out[41]:
In [42]:
not False
Out[42]:
In [43]:
False or not False and True # evaluation order: not, and, or
Out[43]:
In [44]:
# if statement
if x > 0:
print('positive')
In [45]:
# if/else statement
if x > 0:
print('positive')
else:
print('zero or negative')
In [46]:
# if/elif/else statement
if x > 0:
print('positive')
elif x == 0:
print('zero')
else:
print('negative')
In [47]:
# single-line if statement (sometimes discouraged)
if x > 0: print('positive')
In [48]:
# single-line if/else statement (sometimes discouraged), known as a 'ternary operator'
'positive' if x > 0 else 'zero or negative'
Out[48]:
In [49]:
# create an empty list (two ways)
empty_list = []
empty_list = list()
In [50]:
# create a list
simpsons = ['homer', 'marge', 'bart']
In [51]:
# print element 0
simpsons[0]
Out[51]:
In [52]:
len(simpsons)
Out[52]:
In [53]:
# append element to end
simpsons.append('lisa')
simpsons
Out[53]:
In [54]:
# append multiple elements to end
simpsons.extend(['itchy', 'scratchy'])
simpsons
Out[54]:
In [55]:
# insert element at index 0 (shifts everything right)
simpsons.insert(0, 'maggie')
simpsons
Out[55]:
In [56]:
# search for first instance and remove it
simpsons.remove('bart')
simpsons
Out[56]:
In [57]:
# remove element 0 and return it
simpsons.pop(0)
Out[57]:
In [58]:
# remove element 0 (does not return it)
del simpsons[0]
simpsons
Out[58]:
In [59]:
# replace element 0
simpsons[0] = 'krusty'
simpsons
Out[59]:
In [60]:
# concatenate lists (slower than 'extend' method)
neighbors = simpsons + ['ned', 'rod', 'todd']
neighbors
Out[60]:
In [61]:
# counts the number of instances
simpsons.count('lisa')
Out[61]:
In [62]:
# returns index of first instance
simpsons.index('itchy')
Out[62]:
In [63]:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
In [64]:
# element 0
weekdays[0]
Out[64]:
In [65]:
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]
Out[65]:
In [66]:
# starting point is implied to be 0
weekdays[:3]
Out[66]:
In [67]:
# elements 3 (inclusive) through the end
weekdays[3:]
Out[67]:
In [68]:
# last element
weekdays[-1]
Out[68]:
In [69]:
# every 2nd element (step by 2)
weekdays[::2]
Out[69]:
In [70]:
# backwards (step by -1)
weekdays[::-1]
Out[70]:
In [71]:
# alternative method for returning the list backwards
list(reversed(weekdays))
Out[71]:
In [72]:
simpsons.sort()
simpsons
Out[72]:
In [73]:
# sort in reverse
simpsons.sort(reverse=True)
simpsons
Out[73]:
In [74]:
# sort by a key
simpsons.sort(key=len)
simpsons
Out[74]:
In [75]:
sorted(simpsons)
Out[75]:
In [76]:
sorted(simpsons, reverse=True)
Out[76]:
In [77]:
sorted(simpsons, key=len)
Out[77]:
In [78]:
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)
num
Out[78]:
In [79]:
# create a second reference to the same list
same_num = num
In [80]:
# modifies both 'num' and 'same_num'
same_num[0] = 0
print(num)
print(same_num)
In [81]:
# copy a list (two ways)
new_num = num[:]
new_num = list(num)
In [82]:
num is same_num # checks whether they are the same object
Out[82]:
In [83]:
num is new_num
Out[83]:
In [84]:
num == same_num # checks whether they have the same contents
Out[84]:
In [85]:
num == new_num
Out[85]:
In [86]:
# create a tuple directly
digits = (0, 1, 'two')
In [87]:
# create a tuple from a list
digits = tuple([0, 1, 'two'])
In [88]:
# trailing comma is required to indicate it's a tuple
zero = (0,)
In [89]:
digits[2]
Out[89]:
In [90]:
len(digits)
Out[90]:
In [91]:
# counts the number of instances of that value
digits.count(0)
Out[91]:
In [92]:
# returns the index of the first instance of that value
digits.index(1)
Out[92]:
In [93]:
# elements of a tuple cannot be modified (this would throw an error)
# digits[2] = 2
In [94]:
# concatenate tuples
digits = digits + (3, 4)
digits
Out[94]:
In [95]:
# create a single tuple with elements repeated (also works with lists)
(3, 4) * 2
Out[95]:
In [96]:
# sort a list of tuples
tens = [(20, 60), (10, 40), (20, 30)]
sorted(tens) # sorts by first element in tuple, then second element
Out[96]:
In [97]:
# tuple unpacking
bart = ('male', 10, 'simpson') # create a tuple
(sex, age, surname) = bart # assign three values at once
print(sex)
print(age)
print(surname)
In [98]:
# convert another data type into a string
s = str(42)
s
Out[98]:
In [99]:
# create a string directly
s = 'I like you'
In [100]:
s[0]
Out[100]:
In [101]:
len(s)
Out[101]:
In [102]:
s[:6]
Out[102]:
In [103]:
s[7:]
Out[103]:
In [104]:
s[-1]
Out[104]:
In [105]:
s.lower()
Out[105]:
In [106]:
s.upper()
Out[106]:
In [107]:
s.startswith('I')
Out[107]:
In [108]:
s.endswith('you')
Out[108]:
In [109]:
# checks whether every character in the string is a digit
s.isdigit()
Out[109]:
In [110]:
# returns index of first occurrence, but doesn't support regex
s.find('like')
Out[110]:
In [111]:
# returns -1 since not found
s.find('hate')
Out[111]:
In [112]:
# replaces all instances of 'like' with 'love'
s.replace('like', 'love')
Out[112]:
In [113]:
# split a string into a list of substrings separated by a delimiter
s.split(' ')
Out[113]:
In [114]:
# equivalent (since space is the default delimiter)
s.split()
Out[114]:
In [115]:
s2 = 'a, an, the'
s2.split(',')
Out[115]:
In [116]:
# join a list of strings into one string using a delimiter
stooges = ['larry', 'curly', 'moe']
' '.join(stooges)
Out[116]:
In [117]:
# concatenate strings
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
Out[117]:
In [118]:
s5 = ' ham and cheese '
s5.strip()
Out[118]:
In [119]:
# old way
'raining %s and %s' % ('cats', 'dogs')
Out[119]:
In [120]:
# new way
'raining {} and {}'.format('cats', 'dogs')
Out[120]:
In [121]:
# new way (using named arguments)
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')
Out[121]:
In [122]:
# use 2 decimal places
'pi is {:.2f}'.format(3.14159)
Out[122]:
In [123]:
# normal strings allow for escaped characters
print('first line\nsecond line')
In [124]:
# raw strings treat backslashes as literal characters
print(r'first line\nfirst line')