Академический Документы
Профессиональный Документы
Культура Документы
get peanut butter out of pantry get peanut butter out of pantry
spread peanut butter on bread spread peanut butter on bread
put peanut butter back in pantry put peanut butter back in pantry
get peanut butter out of pantry get peanut butter out of pantry
spread peanut butter on bread spread peanut butter on bread
put peanut butter back in pantry put peanut butter back in pantry
The Main
MakePeanutButterSandwichWith(Jelly)
MakePeanutButterSandwichWith(Marshmallow Fluff)
MakePeanutButterSandwichWith(Anchovies)
Methods
In Python (and all programming languages) a method is a
focused algorithm defined to solve a specific problem
For example:
Make PB Sandwich
Calculate sine, cosine, and tangent.
Draw a square
Methods can be passed parameters so they are more general
For example:
Condiment in makePeanutButterSandwichWith
Methods can have any number of parameters (zero to many)
Formally
Formal Method
Methods in Python consist primarily of two components:
Signature
Body
The Signature consist of
The method name
The parameter list
The Body consists of
The algorithm code
An optional return statement.
Well talk about this later
Example
Parameter
Name List
Note: The method signature begins with def and ends with :
Example
x = addTwoValues(2,3)
y = addTwoValues(10,20)
Another Example
x = largerValueTimes10(2,3)
print(x)
Another Example
x = threeValuesLargerValueTimes10(2,3,15)
print(x)
No Inputs
def returnTheValueFour():
return 4
x = returnTheValueFour()
Note: When you define a method with no parameters, you still need the ()
Scope
Variables created in a method die at the end of method
A horrible painful variable death
This is called scope
This also includes parameters
def fooBar(var1, hello, bye):
thing = 2
goo = 55
trick = 100
bah = var1
boo = bye
gah = hello
return thing + goo +trick + bah + boo - gah
def addThreeWeird(a,b,c):
return a + b*2 + c*3
a = 1
b = 100
c = 1000
x = addThreeWeird(c,a,b)
def hello():
print(Hello world)
hello()