Weekly Topics
•
In this weeks lecture and lab we will look at the following areas:
•
Writing functions which perform various tasks,
•
Discussion of arguments and parameters,
•
Creating our own data types as objects via writing Classes,
•
Constructors
•
Providing functionality to those classes via methods,
•
Passing objects around between functions and methods,
3
What is a function?
•
A function is just a named “block of code”, that we can execute by calling it by name!
•
Functions are defined in Python by using the defkeyword, like this:
defsayHello():
print(“Hello!”)
•
In the above example, our function is called sayHello(), it doesn’t take any parameters (which we’ll discuss very shortly), and the entire function is just a single line of code which prints Hello! to the screen.
•
To execute the above function (i.e. make it run), we can simply call the function by name, like this:
sayHello()
4
Why use functions?
•
On the previous slide we saw just a single line function, so you might be wondering why bother -why not just type in print(“Hello!”) whenever we want to display Hello!…
•
…but what if our function was 10 lines, or 100 lines, or 1,000 lines?
•
We wouldn’t want to re-type (or more likely, copy and paste) all that code again each time we wanted to perform the functionality.
•
Also, what if we wanted to modify the function? Do we really want to modify lots of different copies in the exact same way? (No we don’t -not only would it take a long time, what if we made a mistake on one of them?)
•
So by giving a block of code that does some work for us a name, we can refer to it and run it whenever we like just by calling the function -which just means we run the function as a command!
5
Functions and Parameters
•
Our sayHello()function has a set of open and close brackets at the end of it, both when it’s defined, and when we call the function to execute it.
•
They’re empty because the function doesn’t accept any data that we want it to work with -it just prints Hello!and that’s it. But what if we wanted to make the function say Hello, ?
•
In this case we could re-write a function like this:
defsayHello(name):
print( “Hello, 0!”.format(name) )
•
Now when we call the function, we have to provide it with a piece of data (called a parameter), like this:
sayHello(“Bob”)
•
Which will display: Hello, Bob!
6
Functions and Parameters (Cont’d)
•
So, our function definition is this:
defsayHello(name):
print(“Hello, !”.format(name) )
•
And we can execute the function like this:
sayHello(“Bob”)
•
What’s happening is: The data that we provide when we call the function (which is called an actual parameter or argument) gets passedto the function.
•
When this happens, that data gets given its own name for use inside the function (called a formal parameter).
•
So inside thesayHellofunction, the variable called name(formal parameter) stores whatever information we passed to the function when we called it (actual parameter or argument) -which in this case is just the string data “Bob”.
7
Functions and Parameters (Cont’d)
•
So now that our sayHello(name)functiontakes one formal parameter -what will happen if we try to run the function without giving it any data to work with, like this:
sayHello()
•
Python will complain -and rightly so! We promisedPython that our function would be given a single piece of data to work with -and then we didn’t provide that single piece of data!
•
The error message you’ll see if you try to call the function without passing it any parameters will be something like this:
Traceback(most recent call last):
File “C:PythonFunctions.py”, line 13, in
sayHelloName()
TypeError: sayHello() takes exactly 1 argument (0 given)
8
Using Multiple Parameters
•
We’ve seen that we can create a functions that take no parameters, and a single parameter as input to work with -but we can also write functions that take multiple parameters just as easily:
defprintSum(firstNum, secondNum):
sum = firstNum+ secondNum
print( “The sum of the numbers is 0”.format(sum) )
•
We could then use the above function like this:
printSum(5, 3)
•
Which will display:
The sum of the numbers is 8
9
Using Multiple Parameters (Cont’d)
•
When using our printSumfunction, we could call it like this:
printSum(5, 3)
printSum(3, 5)
•
Both of the above calls will produce the exact same output, because it doesn’t matter if we add 5 plus 3, or if we add 3 plus 5 -either way the answer is always 8!
•
In the first case:
firstNumwill be 5, and secondNumwill be 3.
•
While in the second case:
firstNumwill be 3, and secondNumwill be 5.
•
No problems so far…
10
Using Multiple Parameters (Cont’d)
This won’t work because our printSumfunction takes
two parameters and we aren’t giving it anyparameters!
printSum()
This won’t work because our printSumfunction takes two
parameters and we’re only giving it oneparameter!
printSum(5)
This WILL work because our printSumfunction takes two# parameters, and we’re giving it two parameters! Hurrah!
printSum(5, 3)
This won’t work because our printSumfunction takes two
parameters and now we’re giving it threeparameters! That’s# too many parameters!printSum(5, 3, 1)
Quiz: What about if we called printSum(“5”, “3”) -would that work?
11
The Order of Parameters
•
Now let’s look at a function where the order of the parameters is more important. If we had a function that took two parameters and used them like this:
defdisplayFavourites(number, food):
print( “Favenumber: 0. Food: 1”.format(number, food) )
•
Then if we called the function like below we wouldn’t have any problems:
displayFavourites(6, “Pizza”)
Favenumber: 6 Food: Pizza
•
But what would happen if we called it like this?:
displayFavourites(“Pizza”, 6)
12
Pass By Value
•
When we provide arguments (i.e. actual parameters) to functions, Python uses a scheme called “Pass By Value” to do so.
•
This means that the values provided get assigned to the formal parameters of the function as, essentially, copiesof the actual parameters.
•
The knock-on effect of this is that if we modify the actual parameters inside the function, those changes are not made to the arguments!
•
That is, the changes are only made to the copies -and not the original data!
•
Let’s take a look at this in action…
13
Pass By Value (Cont’d)
Function to add five to a number
defaddFive(number):
number += 5
print( “Inside addFive, number is 0”.format(number) )
luckyNumber= 6
print(“Initially, luckyNumberis 0”.format(luckyNumber) )
Run our addFivefunction, passing it luckyNumberas a parameter
addFive(luckyNumber)
print(“Final luckyNumbervalue is 0”.format(luckyNumber) )
•
When we run the above, the final line prints out:
Final luckyNumbervalue is 6
So only the copy of our luckyNumbervariable got modified -the original remains unchanged!
14
Returning a Value from a Function
•
But what if we want a function to do some work for us (like adding five to a number, such as in the last example) -and then we want to keepour new value?
•
To do that, we have toreturnthe “answer” from our function using the return statement!
•
This will also change the way in which we call the function, because when we ask a function to do some work, we’ll now want to store the answer that we get back using the assignment operator (i.e. the ‘equals’ sign!).
•
Let’s rewrite our previous addFivefunction to add five to a number, and then pass us back the new value for us to use…
15
Returning a Value from a Function (Cont’d)
Function to add five to a number and return the result
defaddFive(number):
number += 5
return number
luckyNumber= 6
print( “Initially, luckyNumberis 0”.format(luckyNumber) )
Run our addFivefunction, passing it luckyNumberas a
parameter and then assigning the result back to luckyNumber
luckyNumber= addFive(luckyNumber)
print( “But now, luckyNumberis: 0”.format(luckyNumber) )
•
Running this version does modify our luckyNumbervariable, because we assign the value returned from the function back to the variable (i.e. we overwrite its original value with the new value!).
16
Returning a Value from a Function (Cont’d)
•
We don’t have to store the result of running the function back in any of the variables we passed to the function, for example we can happily go:
defaddFive(number):
number += 5
return number
increasedValueis created and assigned the value 20
increasedValue= addFive(15)
anotherValueis created and assigned the value 25 here
anotherValue= addFive(increasedValue)
And so on…
17
Returning a Value from a Function (Cont’d)
•
Also, we don’t have to store the result passed back from a function at all! We may decide to use it directly, or do absolutely nothing with it!
Function to square a number and return the result
defsquareNumber(theNumber):
return theNumber* theNumber
print(“3 squared is 0”.format( squareNumber(3) ) )
•
Or:
This goes and squares 999 -but the result is never used
squareNumber(999)
18
Multiple Assignment
•
Unlike most programming languages, Python allows us to specify multiple values to return from a function -and we can do this by simply listing the values we’d like to return separated by commas (i.e. 1,3,5 ).
•
But before we do that, let’s look at a little bit of multiple assignment.
•
We’ve seen that we can specify the value for a variable, like this:
someNumber= 123
•
But we can also create and assign multiple variables in one statement, like this:
day, month, year = 7, 3, 1988
print(“My birthday is //”.format(day, month, year) )
•
Which will display: My birthday is 7/3/1988
19
Multiple Assignment (Cont’d)
•
By allowing us to both assign and returnmultiple values at once by separating them by commas, we can now do things like swap the value of two variables, like this:
Multiple assign highTempas 34 and lowTempas 15
highTemp, lowTemp= 34, 15
Function to swap values
defswapValues(a, b):
return b, a
Swap the values via above function
highTemp, lowTemp= swapValues(highTemp, lowTemp)
print(highTemp) # highTempis now 15
print(lowTemp) # lowTempis now 34
Swap back so highTempis 34 and lowTemp15 again!
highTemp, lowTemp= lowTemp, highTemp
20
Multiple Assignment (Cont’d)
•
Let’s do another example of returning multiple values from a function:
Function to take two values and return the result of# adding them and then subtracting them
defaddAndSubtract(num1, num2):
addResult= num1 + num2
subtractResult= num1 -num2
return addResult, subtractResult
added, subtracted = addAndSubtract(5, 3)
print(added)# 8
print(subtracted)# 2
•
Let’s do one final example, this time to find the highest and lowest values in a list…
21
Multiple Assignment (Cont’d)
•
This time we’re going to write a function that takes a listof numbers, andreturns us the lowestnumber, and the highestnumber (in that order!):
deffindMinAndMax(list):
min = list[0] # Assign min as the 1st element in the list
max = list[0] # Assign max as the 1st element in the list
for value in list:# Loop through all elements & adjust!
if (value < min): min = value if (value > max):
max = value
return min, max
lottoNumbers= [17, 9, 22, 44, 37, 5]
min, max = findMinAndMax(lottoNumbers)
print(“lowest is 0, highest is 1”.format(min, max) )
22
Multiple Assignment (Cont’d)
•
What do you think happens if you return multiple items from a function into a single variable? For example:
defgiveMeTheBeatles():
return “John”, “Paul”, “George”, “Ringo”
beatles= giveMeTheBeatles()
•
When this happens, then Python is smart enough to return us a list! So, we can now access each element by its index, like this:
print(beatles[0]) # John
print(beatles[1]) # Paul
print(beatles[2]) # George
print(beatles[3]) # Ringo
Note: You either get each value separately or all values in a single list, you can’t go firstHalf, secondHalf= giveMeTheBeatles() and expect a list of two items in each of the firstHalf/secondHalfvariables -it won’t work!
23
Wrap up
•
Writing simple functions,
•
Passing and returning data from functions via arguments, parameters and return statements,
The post Week 5 –Functions Methods and Lab Quiz appeared first on My Assignment Online.