Difference between revisions of "Python functions"
From MyWiki
| (5 intermediate revisions by the same user not shown) | |||
| Line 20: | Line 20: | ||
print(add_numbers(1, 2, flag=True)) | print(add_numbers(1, 2, flag=True)) | ||
| + | </source> | ||
| + | <br> | ||
| + | <source lang="python"> | ||
| + | def add_numbers(x,y): | ||
| + | return x+y | ||
| + | |||
| + | a = add_numbers | ||
| + | a(1,2) | ||
| + | </source> | ||
| + | |||
| + | Types and sequences | ||
| + | <source lang="python"> | ||
| + | type('This is a string') | ||
| + | type(None) | ||
| + | type(1) | ||
| + | type(1.0) | ||
| + | type(add_numbers) | ||
| + | |||
| + | x = (1, 'a', 2, 'b') | ||
| + | type x tuples are immutable wheras lists are mutable | ||
| + | x = [1, 'a', 2, 'b'] list | ||
| + | x.append(3.3) | ||
| + | |||
| + | for item in x: | ||
| + | print(item) | ||
| + | OR | ||
| + | i=0 | ||
| + | while( i != len(x) ): | ||
| + | print(x[i]) | ||
| + | i = i + 1 | ||
| + | |||
| + | [1,2] + [3,4] | ||
| + | |||
| + | [1]*3 | ||
| + | |||
| + | 1 in [1, 2, 3] | ||
| + | |||
| + | x[-4:-2] | ||
| + | |||
| + | firstname = 'Christopher' | ||
| + | lastname = 'Brooks' | ||
| + | |||
| + | print(firstname + ' ' + lastname) | ||
| + | print(firstname*3) | ||
| + | print('Chris' in firstname) | ||
| + | |||
| + | 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) | ||
| + | |||
| + | 'Chris' + 2 | ||
| + | 'Chris' + str(2) | ||
| + | |||
| + | x = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'} | ||
| + | x['Christopher Brooks'] # Retrieve a value by using the indexing operator | ||
| + | |||
| + | x['Kevyn Collins-Thompson'] = None | ||
| + | x['Kevyn Collins-Thompson'] | ||
| + | |||
| + | for name in x: | ||
| + | print(x[name]) | ||
| + | |||
| + | for email in x.values(): | ||
| + | print(email) | ||
| + | |||
| + | for name, email in x.items(): | ||
| + | print(name) | ||
| + | print(email) | ||
| + | |||
| + | x = ('Christopher', 'Brooks', 'brooksch@umich.edu') | ||
| + | fname, lname, email = x | ||
| + | |||
| + | x = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor') | ||
| + | fname, lname, email = x | ||
| + | |||
| + | more on strings | ||
| + | |||
| + | 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_r | ||
| + | </source> | ||
| + | Reading and writing CSV files | ||
| + | <source lang="python"> | ||
| + | import csv | ||
| + | |||
| + | %precision 2 | ||
| + | |||
| + | with open('mpg.csv') as csvfile: | ||
| + | mpg = list(csv.DictReader(csvfile)) | ||
| + | |||
| + | mpg[:3] # The first three dictionaries in our list. | ||
| + | == | ||
| + | len(mpg) | ||
| + | == | ||
| + | mpg[0].keys() | ||
| + | == | ||
| + | sum(float(d['cty']) for d in mpg) / len(mpg) | ||
| + | == | ||
| + | sum(float(d['hwy']) for d in mpg) / len(mpg) | ||
| + | == | ||
| + | |||
| + | cylinders = set(d['cyl'] for d in mpg) | ||
| + | cylinders | ||
| + | |||
| + | == | ||
| + | CtyMpgByCyl = [] | ||
| + | |||
| + | 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 | ||
| + | |||
| + | == | ||
| + | vehicleclass = set(d['class'] for d in mpg) # what are the class types | ||
| + | vehicleclass | ||
| + | |||
| + | === | ||
| + | |||
| + | 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 | ||
| + | |||
| + | |||
| + | </source> | ||
| + | Dates and times | ||
| + | <source lang="python"> | ||
| + | import datetime as dt | ||
| + | import time as tm | ||
| + | |||
| + | tm.time() | ||
| + | |||
| + | == | ||
| + | dtnow = dt.datetime.fromtimestamp(tm.time()) | ||
| + | dtnow | ||
| + | == | ||
| + | |||
| + | dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime | ||
| + | |||
| + | == | ||
| + | |||
| + | delta = dt.timedelta(days = 100) # create a timedelta of 100 days | ||
| + | delta | ||
| + | |||
| + | == | ||
| + | today = dt.date.today() | ||
| + | today - delta # the date 100 days ago | ||
| + | today > today-delta # compare dates | ||
| + | |||
| + | </source> | ||
| + | Objects and map() | ||
| + | <source lang = "python"> | ||
| + | |||
| + | class Person: | ||
| + | department = 'School of Information' #a class variable | ||
| + | |||
| + | def set_name(self, new_name): #a method | ||
| + | self.name = new_name | ||
| + | def set_location(self, new_location): | ||
| + | self.location = new_location | ||
| + | |||
| + | person = Person() | ||
| + | person.set_name('Christopher Brooks') | ||
| + | person.set_location('Ann Arbor, MI, USA') | ||
| + | print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department)) | ||
| + | |||
| + | |||
</source> | </source> | ||
Latest revision as of 09:46, 28 July 2019
def add_numbers(x,y,z=None): if (z==None): return x+y else: return x+y+z print(add_numbers(1, 2)) print(add_numbers(1, 2, 3))
def add_numbers(x, y, z=None, flag=False): if (flag): print('Flag is true!') if (z==None): return x + y else: return x + y + z print(add_numbers(1, 2, flag=True))
def add_numbers(x,y): return x+y a = add_numbers a(1,2)
Types and sequences
type('This is a string') type(None) type(1) type(1.0) type(add_numbers) x = (1, 'a', 2, 'b') type x tuples are immutable wheras lists are mutable x = [1, 'a', 2, 'b'] list x.append(3.3) for item in x: print(item) OR i=0 while( i != len(x) ): print(x[i]) i = i + 1 [1,2] + [3,4] [1]*3 1 in [1, 2, 3] x[-4:-2] firstname = 'Christopher' lastname = 'Brooks' print(firstname + ' ' + lastname) print(firstname*3) print('Chris' in firstname) 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) 'Chris' + 2 'Chris' + str(2) x = {'Christopher Brooks': 'brooksch@umich.edu', 'Bill Gates': 'billg@microsoft.com'} x['Christopher Brooks'] # Retrieve a value by using the indexing operator x['Kevyn Collins-Thompson'] = None x['Kevyn Collins-Thompson'] for name in x: print(x[name]) for email in x.values(): print(email) for name, email in x.items(): print(name) print(email) x = ('Christopher', 'Brooks', 'brooksch@umich.edu') fname, lname, email = x x = ('Christopher', 'Brooks', 'brooksch@umich.edu', 'Ann Arbor') fname, lname, email = x more on strings 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_r
Reading and writing CSV files
import csv %precision 2 with open('mpg.csv') as csvfile: mpg = list(csv.DictReader(csvfile)) mpg[:3] # The first three dictionaries in our list. == len(mpg) == mpg[0].keys() == sum(float(d['cty']) for d in mpg) / len(mpg) == sum(float(d['hwy']) for d in mpg) / len(mpg) == cylinders = set(d['cyl'] for d in mpg) cylinders == CtyMpgByCyl = [] 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 == vehicleclass = set(d['class'] for d in mpg) # what are the class types vehicleclass === 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
Dates and times
import datetime as dt import time as tm tm.time() == dtnow = dt.datetime.fromtimestamp(tm.time()) dtnow == dtnow.year, dtnow.month, dtnow.day, dtnow.hour, dtnow.minute, dtnow.second # get year, month, day, etc.from a datetime == delta = dt.timedelta(days = 100) # create a timedelta of 100 days delta == today = dt.date.today() today - delta # the date 100 days ago today > today-delta # compare dates
Objects and map()
class Person: department = 'School of Information' #a class variable def set_name(self, new_name): #a method self.name = new_name def set_location(self, new_location): self.location = new_location person = Person() person.set_name('Christopher Brooks') person.set_location('Ann Arbor, MI, USA') print('{} live in {} and works in the department {}'.format(person.name, person.location, person.department))