In [6]:
def add_numbers(x,y):
return x+y
a = add_numbers
a(1,2)
Out[6]:
In [15]:
x = [1, 2, 4]
In [16]:
x.insert(2, 3) # list.insert(position, item)
In [17]:
x
Out[17]:
In [18]:
x = 'This is a string'
print(x[0]) #first character
print(x[0:1]) #first character, but we have explicitly set the end character
print(x[0:2]) #first two characters
In [26]:
x = 'This is a string'
pos = 0
for i in range(len(x) + 1):
print(x[0:pos])
pos += 1
pos -= 2
for i in range(len(x) + 1):
print(x[0:pos])
pos -= 1
^ Looks like Augusto de Campos' poems ^.^
In [27]:
firstname = 'Christopher Arthur Hansen Brooks'.split(' ')[0] # [0] selects the first element of the list
lastname = 'Christopher Arthur Hansen Brooks'.split(' ')[-1] # [-1] selects the last element of the list
print(firstname)
print(lastname)
In [30]:
secondname = 'Christopher Arthur Hansen Brooks'.split(' ')[1]
secondname
Out[30]:
In [31]:
thirdname = 'Christopher Arthur Hansen Brooks'.split(' ')[2]
thirdname
Out[31]:
In [32]:
dict = {'Manuel' : 'manuel@company.com', 'Bill' : 'bill@ig.com'}
dict['Manuel']
Out[32]:
In [34]:
for email in dict:
print(dict[email])
In [35]:
for email in dict.values():
print(email)
In [36]:
for name in dict.keys():
print(name)
In [53]:
for name, email in dict.items():
print(name)
print(email)
In [54]:
sales_record = {
'price': 3.24,
'num_items': 4,
'person': 'Chris'}
sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format(sales_record['person'],
sales_record['num_items'],
sales_record['price'],
sales_record['num_items']*sales_record['price']))
In [60]:
import csv
%precision 2 # float point precision for printing to 2
with open('mpg.csv') as csvfile: #read the csv file
mpg = list(csv.DictReader(csvfile)) # https://docs.python.org/2/library/csv.html
# csv.DictReader(csvfile, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)
mpg[:3] # The first three dictionaries in our list.
Out[60]:
In [62]:
len(mpg) # list of 234 dictionaries
Out[62]:
In [64]:
mpg[0].keys() # the names of the colums
Out[64]:
In [69]:
# How to find the average cty fuel economy across all cars.
# All values in the dictionaries are strings, so we need to
# convert to float.
sum(float(d['cty']) for d in mpg) / len(mpg)
Out[69]:
In [70]:
# Similarly this is how to find the average hwy fuel economy across
# all cars.
sum(float(d['hwy']) for d in mpg) / len(mpg)
Out[70]:
In [73]:
# Use set to return the unique values for the number of cylinders
# the cars in our dataset have.
cylinders = set(d['cyl'] for d in mpg)
cylinders
# A set is an unordered collection of items. Every element is unique
# (no duplicates) and must be immutable (which cannot be changed).
# >>> x = [1, 1, 2, 2, 2, 2, 2, 3, 3]
# >>> set(x)
# set([1, 2, 3])
Out[73]:
In [75]:
CtyMpgByCyl = [] # empty list to start the calculations
for c in cylinders: # iterate over all the cylinder levels
summpg = 0
cyltypecount = 0
for d in mpg: # iterate over all dictionaries
if d['cyl'] == c: # if the cylinder level type matches,
summpg += float(d['cty']) # add the cty mpg
cyltypecount += 1 # increment the count
CtyMpgByCyl.append((c, summpg / cyltypecount)) # append the tuple ('cylinder', 'avg mpg')
CtyMpgByCyl.sort(key=lambda x: x[0])
CtyMpgByCyl
# the city fuel economy appears to be decreasing as the number of cylinders increases
Out[75]:
In [77]:
# Use set to return the unique values for the class types in our dataset.
vehicleclass = set(d['class'] for d in mpg) # what are the class types
vehicleclass
Out[77]:
In [79]:
# how to find the average hwy mpg for each class of vehicle in our dataset.
HwyMpgByClass = []
for t in vehicleclass: # iterate over all the vehicle classes
summpg = 0
vclasscount = 0
for d in mpg: # iterate over all dictionaries
if d['class'] == t: # if the cylinder amount type matches,
summpg += float(d['hwy']) # add the hwy mpg
vclasscount += 1 # increment the count
HwyMpgByClass.append((t, summpg / vclasscount)) # append the tuple ('class', 'avg mpg')
HwyMpgByClass.sort(key=lambda x: x[1])
HwyMpgByClass
Out[79]:
In [81]:
import datetime as dt
import time as tm
In [82]:
# time returns the current time in seconds since the Epoch. (January 1st, 1970)
tm.time()
Out[82]:
In [83]:
# Convert the timestamp to datetime.
dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
Out[83]:
In [84]:
dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime
Out[84]:
In [85]:
# timedelta is a duration expressing the difference between two dates.
delta = dt.timedelta(days = 100) # create a timedelta of 100 days
delta
Out[85]:
In [3]:
a = (1, 2)
In [4]:
type(a)
Out[4]:
In [5]:
['a', 'b', 'c'] + [1, 2, 3]
Out[5]:
In [6]:
type(lambda x: x+1)
Out[6]:
In [7]:
[x**2 for x in range(10)]
Out[7]:
In [19]:
str = "Python é muito legal"
lista = []
soma = 0
lista = str.split()
lista
Out[19]:
In [20]:
len(lista[0])
Out[20]:
In [21]:
for i in lista:
soma += len(i)
In [22]:
soma
Out[22]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: