Sei sulla pagina 1di 12

Python 3.2.2 Mathematics, loops, Boolean logic and testing. Mathematics >>> math.__doc__ 'This module is always available.

It provides access to the\nmathematical functions defined by the C standard.' + #Addition #Subtraction / #Floating point division i.e. 11 / 2 --> 5.6 // #Division that rounds down i.e. 11 // 2 == 5 and -11 // 2 == -6 * #Multiplication ** #Exponent ! #Factorial % #Gives the remainder after integer division. 11 % 2 == 1 pow(5, 4) #5 to the power of 4, (Same as 5 ** 4) abs(-5) #Absolute value. >>> import fractions >>> x = fractions.Fraction(1, 3) >>> x Fraction(1, 3) #Returns a fraction type object >>> x * 2 Fraction(2, 3) >>> fractions.Fraction(6, 4) Fraction(3, 2) >>> fractions.Fraction(0, 0) Modules >>> import math #Import the math module >>> math.pi #Constant stored in module 3.1415926535897931 >>> math.sin(math.pi / 2) #Module includes sin(), cos(), tan(), asin(), etc. 1.0 >>> math.tan(math.pi / 4) 0.99999999999999989 #Python isn t perfectly precise >>> math.floor(18.7) #Rounds down, delivers an integer. 18 >>> math.sqrt(81) #Square root 9.0 Assign these functions as variables for easier access >>> sqrt = math.sqrt >>> sqrt(9) 3

Python 3.2.2 Loops, logic and testing while (argument): #loop for (variable) in (list) #First loop: variable=listitem1. Second loop:variable=listitem2... += #x = x + Useful for iterations e.g. while b <= 10: print(b), b += 1 -= #x = x if (test condition): #Runs if condition is true. elif #Runs if previous test condition is false. else #Runs if original test condition is false. in #Checks if a string is in a list etc. e.g. if key5 in dictionary: runsomething, else: runsomethingelse x = pizzahut z in x true or is z in x: run1, else: run2 is #Checks if two things are the same object. If two objects have same values e.g. identical lists, if they are different objects, a is b returns false. print() print("There are <", 2**32, "> possibilities!", sep="") There are <4294967296> possibilities!

Python 3.2.2 Boolean Tests must be proceeded by a colon. == #Eqaulity != #Not equal to If == is used between two equivalent variables or lists, it will give true. x = y = [21, 32, 43] #x and y are the same object >>> x is y True a = [11, 12, 13] b = [11. 12. 13] # b is a different object yet equivalent to a >>> a is b False If is statement is used between two different objects, returns false. <, >, <, >, <=, >= #Strings are compared by their alphabetical place. and, or #Tests numerical or alphabetical Zero values are false, non-zero values are true. >>> def is_it_true(anything): #Defining a function if anything: #Returning true or false print( Yes, it s true. ) else: print( No, it s false. ) >>> import fractions >>> is_it_true(fractions.Fraction(1, 2) #Fraction(0, n) returns false for all n. Yes, it s true. Caution: If Python tests digit with any rounding error e.g. 0.000000001 instead of 0, will return true.

If x == 2: If x == animal: print( abcdef ) else: print( zzzz ) elif x == 3: print( ghijkl ) else: print( alternate )

#Test condition #Nested if statement runs if the original if is true.

Python 3.2.2

Strings \ >>> This is a string [5] i %s %i %f >>> string = "Hello%s" >>> print(string % ' Jay') Hello Jay >>> print(string% ', How are', 'you?') Hello, How are you? >>> string = 'My number is %.2f' >>> from math import pi >>> print(string % pi) My number is 3.14

#Escape charactersIgnores the next symbol #e.g. He\ s an athlete. or Jay said \ Hi\ . #Strings are indexed with place numbers like lists.

#string # converts to integer # converts to float

sentence = "Hello %s, how's your %s" #Allows string variables noun = ("Jay", "head") #Defines the variables print(sentence % noun) #Prints the result Before the %, type the string with missing variables. After the %, type the variables. string = "abc123def" len(string) 9 string.find("de") string.lower() string.replace("old", "new") #Defining a string as variable 'string'.

#Displays the entry number that 'de' starts (==6) #Makes string lowercase. Empty parameters. #replaces part of a string.

Cannot concatenate a string and a number num = str(18) #Convert a number as a string. print( String + num) #Output new string to the user. >>> num1 = 20 >>> num2 = 77 >>> print( The value is ), num1, num2 The value is (None, 20, 77) #Why is None there??

Python 3.2.2

Lists A list is an ordered set of items. Generally, square brackets are used for recalling, curly brackets are used in defining dictionaries and round brackets are used for tuples and in functions. list('Hello') ['H', 'e', 'l', 'l', 'o'] Lists = ['a', 'b', 'c'] Lists[0] 'a' >>> Lists[1] = d >>> Lists ['a', 'd', 'c'] >>> Lists[2:]=list("zyx") >>> Lists [a, b, z, y, x] Lists[3:3]=list("what") List[1:8:2] List[10:0:-2] List[::-2]

#Makes string characters list entries #Defining a list named 'Lists'. #Selecting the first (0) value. #Redefining the second list item. #Recalling list. #Replaces entry 2 onwards with ['z', 'y', 'x']

#Adds ['w', 'h', 'a', 't'] before entry 3 #Start at 1, end at 7 and go in increments of 2 #Starts at 10, ends at 0 and counts backwards in decrements of 2. #Includes the whole list, counting backwards in decrements of 2.

del Lists[2] #Deleting the third list item. Lists[1:-1]=[] #Deletes middle entries Lists[:]=[] #Makes Lists an empty set sorted('listeNtries') #Sorts this string alphabetical, capitals first >>> [21] * 10 [21, 21, 21, 21, 21, 21, 21, 21, 21, 21]

Python 3.2.2 JOINING A SEQUENCE >>> sequence = ['hey', 'there', 'dude'] >>> glue = 'cheese' >>> glue.join(sequence) #Returns 'heycheesetherecheesedude' numlist = [0,1,2,3,4,5] max(numlist) #max Biggest number in a list 5 min() #s Smallest number in a list sum() #sum len(numlist) #length 6 TUPLES (can t edit but can recall) 12,42,12 Jay = (13, 14,20, 21) Jay[2] #Makes a 3-tuple of (12, 42, 12) #Makes Jay a 4-tuple. Cannot edit tuples. #Recalls entry 2 (==20)

Python 3.2.2 Working with a file >>> fob=open('C:/test/blank.txt', mode='w') >>> fob.write("Written in python")6 >>> fob=open('c:/test/blank.txt', 'r') >>> fob.read(4) 'Writ' >>> fob.read(11) 'ten in pyth' >>> fob.read() #Reads all of it. >>> fob.close() #Close files at the end for memory s sake. Dictionary Useful to store and recall lists of names and ages etc. A dictionary name in parameters is precluded by **, e.g. def dict(**ages, name). Any time you want to include dictionary items in your parameters when using a function, it requires the equal sign e.g. key1=value1 dict={ key1 : value1 , key2 : value2 , key3 : value3 } #Curly braces dict[key2] #square brackets to recall value2 dict.clear() #removes all entries {} >>>newdictionary=dict.copy() #Copy dictionary to new variable newdictionary { key1 : value1 , key2 : value2 , key3 : value3 } >>>( key1 ) in dictionary True >>> ages={'dad':42, 'mom':48, 'lisa':7} >>> for item in ages: print(item) dad lisa mom >>> for item in ages: print(item, ages[item]) dad 42 lisa 7 mom 48

Python 3.2.2 Functions type() #Returns the type of function parameter >>> type(1) <class int > >>> type(1.0) <class float > isinstance() #Check whether a value or variable is of a given type float() #Coerces the input into a float i.e. 2->2.0 int() #Coerces the input into an int i.e. 2.5->2 (TRUNCATES) int() truncates negative numbers towards 0. Floating point numbers are accurate to 15 d.p. >>> name = Sausages >>> u in name s #in checks if something is in a string, list etc. True >>> while 1: name = input("Enter name: ") if name == "quit": break #Breaks a while loop Enter name: Jay Enter name: Tom Enter name: Lisa Enter name: quit >>> >>> def whatsup(x): #Defining functions with variables and using return return "what\'s up " + x >>> print(whatsup("Jay")) what's up Jay >>> def plusten(y): return y + 10 >>> print(plusten(214)) 224 >>> def name(first, last): print("%s %s" % (first, last)) >>> name("Jay", "Smith") Jay Smith Default parameters def name(first= Julius , last= Ceasar ): #Define default name values print( %s %s % (first, last)) >>> name() #Recalls default Julius Ceasar >>> name ( Jay , Smith ) Jay Smith >>> name(last = Awesome ) #Recalls default first, defined last as Awesome Julius Awesome

Python 3.2.2 In defining a function, tuples are marked by *, dictionary marked by **. In using tuples in your parameters, the tuple name must be precluded by *. >>> def list(*food): # * allows us to enter parameters of a tuple print(food) >>> list('apples') ('apples',) >>> list('apples', 'peaches', 'chicken') ('apples', 'peaches', 'chicken') >>> def profile(name, *ages): print(name) print(ages) >>> profile('Jay', 41, 12, 24, 42, 11, 11) Jay (41, 12, 24, 42, 11, 11) #Defines the function. First item is a name. # Proceeding items are a tuple of ages.

Python 3.2.2 Classes and Objects You might have a class named Save for inserting, deleting, changing to save messages. You may have a class for formatting the text etc. Class Chat: name = Jay def insert(self): print( We inserted something ) def delete(self): print( We deleted something ) def change(self, value) : self.name = value >>> c = Chat() c. insert We inserted something >>>c.delete() We deleted something >>>c.name Jay >>>c.change( Jamie ) >>>c.name Jamie >>> class parent: var1='bacon' var2='snausage' >>> class child(parent): var2="toast" Using superclass and subclass, overwriting var2 You can only import a module once. Editing and re-importing into the same IDLE does nothing. You must use reload(moduleFilename) def #Define a function i.e. def nonsense(): print( jajsnjwewj jjqj ) import #Imports program, including variables saved on the other file. import otherFile otherFile.otherFunction() pass #Runs a function defined in another file (otherFile.py) #Does nothing. #defines a function called change #sets the input value as new name variable

Python 3.2.2 __ OBJECT? __ __name__ __main__

#Calls the name of the file holding the code #Calls the name of the file being run

if __name__ == __main__ :

#If this line is contained on the file being run, true. #If this line is on a file being imported, #i.e. being run from a different file, false.

Constructors class new: def __init__(self): #Do the proceeding, without me having to tell you. print( Initialises on its own ) >>> newObject=new() Initialises on its own OBJECT.METHOD() thing = ['hello', 'goodbye', 'hello'] Methods: #thing is a list. #Define object as 'thing'

thing.append(45) #Adds '45' to the end of object 'thing' thing.extend(list) #Add multiple values to the end of 'thing' thing.count('hello') #Counts instances of 'hello' in 'thing', (==2) thing.index(45) #Finds entry number of first instance of 'goodbye' in 'thing'. thing.insert(2, evening ) #Inserts evening after item 1. thing.pop(2) #removes then displays 2nd entry from list. thing.remove(4) or thing.remove('hello') #Removes first instance of (string) or (value) thing.reverse() #Reverses order of entries. thing.sort() #sorts list in ascending >>> class exampleClass: eyes="blue" age=20 def thisMethod(self): return 'This method worked'

>>> exampleClass <class '__main__.exampleClass'> >>> exampleObject=exampleClass() >>> exampleObject.eyes 'blue' >>> exampleObject.age 20 >>> exampleObject.thisMethod() 'This method worked'

Python 3.2.2

>>> class className: def createName(self, name): self.name=name def displayName(self): return self.name def saying(self): print("Hello %s" % self.name)

>>> className <class '__main__.className'> >>> first=className() >>> second=className() >>> first.createName('Jay') >>> second.createName('John') >>> first.displayName() 'Jay' >>> first.saying() Hello Jay >>> class dad: var1="Hello, I am father" >>> class MOM: var2="Hey there, I am MOM" >>> class child(dad, MOM): var3="I'm a new variable"

#Child class (subclass) taking parent class traits

Potrebbero piacerti anche