You have already used many built-in Python functions. Let's list a few:
print()
input()
int()
str()
float()
type()
round()
range()
sqrt()
A function is a block of code that that is executed when the name is called. Once the block finished, the interpreter returns to where the function was called.
The specifications of these built-in functions are listed in the documentation at python.org. That documentation is also installed when you install Python. The API is also available as a tool-tip when you are using IDLE.
import math
degrees = 45
radians = (degrees * math.pi) / 180.0
print(math.sin(radians))
What happened? We used the sin() from the math module to calculate the sine of the angle in radian measure.
No, we are reusing the functions that were written for us to use!
Yes! We will cover defining functions in this lesson.
call - calling / writing the function into our code. Python will look for the function, and run it. When you type print(), Python executes the print function.
pass / passing - putting something into the brackets of the function. Putting a value in the brackets allows you to pass something to the function. Like passing the string 'Hello' to a print() ... print('Hello'). These are called parameters.
return - the value the function returns once it has executed. For instance, if I pass the integer 3 to the float(), 3.0 would be returned. x = float(3) ... there would be a 3.0 in x.
signature - the complete name of the function. The signature indicates the name of the function and the arguments that it will accept.
Functions are action / verb based. Remember that a function does something. The clearer the name, the easier it is for you to write your documentation. Please follow the rules outlined in naming variables and apply them when you are naming a function (except the action / verb).
One.
For re-usability and flexibility, a function should only do one thing. For example, you would not want a getGuessandCheckGuess(). It would be better to have separated your code into getGuess() and checkGuess().
The pseudo code for a defining a function is:
def NAME( LIST OF PARAMETERS ):
STATEMENTS
The keyword def indicates the beginning of the function definition. You'll notice that indentation separates the functions code from the rest of your code. The list of parameters indicates what your function will expect to receive.
def blankLine():
print('')
What does our blankLine() do? It inserts a blank line in our output whenever it is called.
def blankLine():
print('')
print('Hello')
blankLine()
print('Bye')
OUTPUT:
Hello
Bye
So far in this course, Python has executed your code starting from the first line of the file, and it works its way down.
What happens now?
Python reads the functions, but does not execute them because of where they are defined, but rather where they are called. Selection statements and loops alter the flow of the program, functions don't. Think of the function call like a detour. Eventually you have to go back to wherever the function was called.
A user defined function can accept a value(s).
def repeatItTwice(some_string):
for i in range(0,2):
print(some_string)
x = input('Please enter a word: ')
repeatItTwice(x)
OUTPUT:
Please enter a word: hello
hello
hello
>>>
repeatItTwice() is not in the API! I wrote it in the body of my code. When I wanted to use it, I called it.
def printName(fname, lname):
print('Hello ' + fname + ' ' + lname)
x = input('Please enter your first name: ')
y = input('Please enter your last name: ')
printName(x, y)
OUTPUT:
Please enter your first name: Bobo
Please enter your last name: Jonze
Hello Bobo Jonze
>>>
The function we defined, printName(), accepts two variables. x and y are visible to the whole program. But what about the variables fname and lname?
In the previous examples printName() and repeatItTwice() are called with variables. If we look at the signature of repeatItTwice(), you'll see that it accepts a variable. In this case a variable called some_string. This is when scope comes into play. some_string is only visible within the function repeatItTwice().
If you try to access some_string from anywhere else in the code, it will not be seen. After a function runs, all the variables within its scope are destroyed.
The scope of a variable is limited to where it was built.
Ever wonder why we use a variable and an assignment operator with built in functions like input() ? It's because input() returns a value to whatever called it.
Problem: Write a function that accepts two numbers, finds their sum, and returns a value.
def mySum(a, b):
a = int(a)
b = int(b)
answer = a + b
answer = str(answer)
return answer
x = input('Please enter your first number: ')
y = input('Please enter your second number: ')
z = mySum(x, y)
print('The sum of your numbers is: ' + z)
def mySum(a, b):
a = int(a)
b = int(b)
answer = a + b
answer = str(answer) #Where does this happen in my next example?
print('The sum of your numbers is: ' + answer)
x = input('Please enter your first number: ')
y = input('Please enter your second number: ')
mySum(x, y)
Could we introduce another function? Why? Well, it looks like mySum() is doing the math and the printing. This effects the flexibility of mySum().
I mean, it's called mySum(), not mySumAndPrint(), right?
def mySum(a, b):
a = int(a)
b = int(b)
answer = a + b
#What happened to ***answer = str(answer)*** the string casting of answer?
return answer
def printIt(c):
c = str(c) #How is my printIt() better than the built-in print()? HINT: IT CASTS!
print('The sum of your numbers is: ' + c)
x = input('Please enter your first number: ')
y = input('Please enter your second number: ')
z = mySum(x, y)
printIt(z)
That looks better. Arguably, you have two flexible functions. One that will take a number and get it ready for string output, and another that will take two numbers and find their sum. Is there a way to make this even better???
def getNum():
num = input('Please enter your number: ')
return num
def mySum(a, b):
a = int(a)
b = int(b)
answer = a + b
return answer
def printIt(c):
c = str(c)
print('The sum of your numbers is: ' + c)
x = getNum()
y = getNum()
z = mySum(x, y)
printIt(z)
Now, we've got our number input in a function, outside of the 'main' part of our code. We then reuse the function getNum().
One last word on return statements. Once return occurs, control goes back to whatever called that function. That idea sets you up for another interesting possibility:
Some solutions will have multiple return statements. I try to avoid multiple return in my solutions.
def evenOrOdd(a):
if a % 2 == 0:
return 'Even'
else:
return 'Odd'
userinput = input('Please enter a positive number to see if it is even or odd: ')
userinput = int(userinput)
result = evenOrOdd(userinput)
print(result)
It works, but I'd rather not.
Think about functions only doing one thing, and returning one thing (or nothing).
def evenOrOdd(a):
if a % 2 == 0:
foo = 'Even'
else:
foo = 'Odd'
return foo
userinput = input('Please enter a positive number to see if it is even or odd: ')
userinput = int(userinput)
result = evenOrOdd(userinput)
print(result)
You have freedom. Choose.
Some inspiration.