Difference between revisions of "Python functions"
Line 167: | Line 167: | ||
HwyMpgByClass.sort(key=lambda x: x[1]) | HwyMpgByClass.sort(key=lambda x: x[1]) | ||
HwyMpgByClass | 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 = "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> |
Revision as of 09:45, 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()
Invalid language.
You need to specify a language like this: <source lang="html4strict">...</source>
Supported languages for syntax highlighting:
4cs, 6502acme, 6502kickass, 6502tasm, 68000devpac, abap, actionscript, actionscript3, ada, algol68, apache, applescript, apt_sources, arm, asm, asp, asymptote, autoconf, autohotkey, autoit, avisynth, awk, bascomavr, bash, basic4gl, bf, bibtex, blitzbasic, bnf, boo, c, c_loadrunner, c_mac, caddcl, cadlisp, cfdg, cfm, chaiscript, cil, clojure, cmake, cobol, coffeescript, cpp, cpp-qt, csharp, css, cuesheet, d, dcl, dcpu16, dcs, delphi, diff, div, dos, dot, e, ecmascript, eiffel, email, epc, erlang, euphoria, f1, falcon, fo, fortran, freebasic, freeswitch, fsharp, gambas, gdb, genero, genie, gettext, glsl, gml, gnuplot, go, groovy, gwbasic, haskell, haxe, hicest, hq9plus, html4strict, html5, icon, idl, ini, inno, intercal, io, j, java, java5, javascript, jquery, kixtart, klonec, klonecpp, latex, lb, ldif, lisp, llvm, locobasic, logtalk, lolcode, lotusformulas, lotusscript, lscript, lsl2, lua, m68k, magiksf, make, mapbasic, matlab, mirc, mmix, modula2, modula3, mpasm, mxml, mysql, nagios, netrexx, newlisp, nsis, oberon2, objc, objeck, ocaml, ocaml-brief, octave, oobas, oorexx, oracle11, oracle8, oxygene, oz, parasail, parigp, pascal, pcre, per, perl, perl6, pf, php, php-brief, pic16, pike, pixelbender, pli, plsql, postgresql, povray, powerbuilder, powershell, proftpd, progress, prolog, properties, providex, purebasic, pycon, pys60, python, q, qbasic, rails, rebol, reg, rexx, robots, rpmspec, rsplus, ruby, sas, scala, scheme, scilab, sdlbasic, smalltalk, smarty, spark, sparql, sql, stonescript, systemverilog, tcl, teraterm, text, thinbasic, tsql, typoscript, unicon, upc, urbi, uscript, vala, vb, vbnet, vedit, verilog, vhdl, vim, visualfoxpro, visualprolog, whitespace, whois, winbatch, xbasic, xml, xorg_conf, xpp, yaml, z80, zxbasic
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))