Text stringlengths 1 9.41k |
|---|
'Hello' - 'H'
**Exercise 07**
a. Write a statement that assigns the value 79.95 to a variable name
```
subtotal.
```
b. |
Write a statement that assigns the value 0.06 to a variable name
```
tax_rate.
```
c. Write a statement that multiplies subtotal by tax_rate and assigns
the result to a variable name sales_tax.
d. |
Write a statement that adds subtotal and sales_tax and assigns
the result to a variable name total.
-----
**Exercise 08**
What do you think would happen if we were to evaluate the expression
```
1 / 0? |
Why? Does this result in an error? What type of error results?
```
**Exercise 09**
a. |
Now that we’ve learned a little about modular arithmetic, reconsider the numerals we use in our decimal (base 10) system. |
In that
system, why do we have only the numerals 0, 1, 2, 3, 4, 5, 6, 7, 8,
and 9?
b. What numerals would we need in a base 7 system? |
How about base
5?
-----
-----
#### Chapter 5
### Functions
This chapter introduces functions. |
Functions are a fundamental building
block for code in all programming languages (though they may go by
different names, depending on context).
**Learning objectives**
- You will learn how to write simple functions in Python, using def.
- You will learn how to use functions in your code.
- You will learn that... |
We’ll see many others soon.
```
Essentially, a function is a sub-program which we can “call” or “invoke” from within our larger program. |
For example, consider this code
which prints a string to the console.
```
print('Do you want a cookie?')
```
Here we’re making use of built-in Python function print(). |
The developers of Python have written this function for you, so you can use it
within your program. |
When we use a function, we say we are “calling”
or “invoking” the function.
In the example above, we call the print() function, supplying the
string 'Do you want a cookie?' as an argument.
As a programmer using this function, you don’t need to worry about
what goes on “under the hood” (which is quite a bit, actually). |
How
convenient!
When we call a function, the flow of control within our program passes
to the function, the function does its work, and then returns a value. |
All
Python functions return a value, though in some cases, the value returned
is None.[1]
###### Defining a function
Python allows us to define our own functions.[2] A function is a unit
of code which performs some calculation or some task. |
A function may
take zero or more arguments (inputs to the function). |
The definition
of a function may include zero or more formal parameters which are,
essentially, variables that will take on the values of the arguments provided. |
When called, the body of the function is executed. In most, but
not all cases, a value is explicitly returned. |
Returned values might be the
result of a calculation or some status indicator—this will vary depending
on the purpose of the function. |
If a value is not explicitly returned, the
value None is returned implicitly.
Let’s take the simple example of a function which squares a number.
In your mathematics class you might write
𝑓(𝑥) = 𝑥[2]
1Unlike C or Java, there is no such thing as a void function in Python. |
All
Python functions return a value, even if that value is None.
2Different languages have different names for sub-programs we can call within
a larger program, for example, functions, methods, procedures, subroutines, etc.,
and some of these designations vary with context. |
Also, these are defined and implemented somewhat differently in different languages. |
However, the fundamental
idea is similar for all: these are portions of code we can call or invoke within our
programs.
-----
and you would understand that when we apply the function 𝑓 to some
argument 𝑥 the result is 𝑥[2]. |
For example, 𝑓(3) = 9. |
Let’s write a function
in Python which squares the argument supplied:
```
def square(x):
return x * x
def is a Python keyword, short for “define”, which tells Python we’re
```
defining a function. |
(Keywords are reserved words that are part of
the syntax of the language. |
def is one such keyword, and we will see
others soon.) Functions defined with def must have names (a.k.a., “identifiers”),[3] so we give our function the name “square”.
Now, in order to calculate the square of something we need to know
what that something is. |
That’s where the x comes in. We refer to this as
a formal parameter of the function. When we use this function elsewhere
in our code we must supply a value for x. |
Values passed to a function are
called arguments (however, in casual usage it’s not uncommon to hear
people use “parameter” and “argument” interchangeably).
At the end of the first line of our definition we add a colon. |
What
follows after the colon is referred to as the body of the function. It is
within the body of the function that the actual work is done. |
The body
of a function must be indented as shown below—this is required by the
syntax of the language. |
It is important to note that the body of the
_function is only executed when the function is called, not when it is_
_defined._
In this example, we calculate the square, x * x, and we return the
result. |
return is a Python keyword, which does exactly that: it returns
some value from a function.
Let’s try this in the Python shell to see how it works:
```
>>> def square(x):
... |
return x * x
...
>>>
```
Here we’ve defined the function square(). Notice that if we enter this
in the shell, after we hit return after the colon, Python replies with ...
and indents for us. |
This is to indicate that Python expects the body
of the function to follow. Remember: The body of a function must be
indented. |
Indentation in Python is syntactically significant (which might
seem strange if you’ve coded in Java, C, C++, Rust, JavaScript, C#,
_etc.; Python uses indentation rather than braces)._
So we write the body—in this case, it’s just a single line. |
Again,
Python replies with ..., essentially asking “Is there more?”. |
Here we
hit the return/enter key, and Python understands we’re done, and we
wind up back at the >>> prompt.
Now let’s use our function by calling it. |
To call a function, we give
the name, and we supply the required argument(s).
3Python does allow for anonymous functions, called “lambdas”, but that’s for
another day. |
For the time being, we’ll be defining and calling functions as demonstrated here.
-----
```
>>> square(5) # call `square` with argument 5
25
>>> square(7) # call `square` with argument 7
49
>>> square(10) # call `square` with argument 10
100
```
Notice that once we define our function we can reuse it ov... |
This is one of the primary motivations for functions.
Notice also that in this case, there is no x outside the body of the
function.
```
>>> x
Traceback (most recent call last):
File "/blah/blah/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
NameError: name 'x'... |
The function then calculates x * x and returns
the value which is the result of this calculation.
If we wish to use the value returned by our function we can save it by
assigning the value to some variable, or use it in an expression, or even
include it as an argument to another function!
###### Can we create new vari... |
Of course.
```
def cube(x):
y = x ** 3 # assign result local variable `y`
return y # return the value of `y`
```
We refer to such variable names (y in this example) as local variables,
and like the formal parameters of a function, they exist only within the
body of the function.
4This is what is called “sco... |
It does not exist outside the function—for this we say “x
is out of scope.” We’ll learn more about scope later.
-----
###### Storing a value returned by a function
Continuing with our example of square():
```
>>> a = 17
>>> b = square(a)
>>> b
289
```
Notice that we can supply a variable as an argument to ... |
Let’s use the value returned by the square() function to
calculate the circumference of a circle of radius 𝑟.
```
>>> PI = 3.1415926
>>> r = 126.1
>>> PI * square(r)
49955.123667046
```
Notice we didn’t assign the value returned to a variable first, but
rather, we used the result directly in an expression.
#... |
We pass the value 12 to the square() function,
this calculates the square and returns the result (144). |
This result becomes the value we pass to the print() function, and, unsurprisingly,
Python prints 144.
###### Do all Python functions return a value?
This is a reasonable question to ask, and the answer is “yes.”
But what about print()? |
Well, the point of print() is not to return
some value but rather to display something in the console. We call things
that a function does apart from returning a value side effects. |
The side
effect of calling print() is that it displays something in the console.
5In fact, even though it’s syntactically valid for a variable in the outer scope to
have the same name as a parameter to a function, or a local variable within a function, it’s best if they don’t have the same identifier. |
See the section on “shadowing”
for more.
-----
```
>>> print('My hovercraft is full of eels!')
My hovercraft is full of eels!
```
But does print() return a value? How would you find out? |
Can you
think of a way you might check this?
What do you think would happen here?
```
>>> mystery = print('Hello')
```
Let’s see:
```
>>> mystery = print('Hello')
Hello
>>> print(mystery)
None
None is Python’s special way of saying “no value.” None is the default value
```
returned by functions which don’t ... |
All Python
functions return a value, though in some cases that value is None.[6] So
```
print() returns the None.
```
How do we return None (assuming that’s something we want to do)?
By default, in the absence of any return statement, None will be returned
implicitly.
```
>>> def nothing():
... |
pass # `pass` means "don't do anything"
...
>>> type(nothing())
<class 'NoneType'>
```
Using the keyword return without any value will also return None.
```
>>> def nothing():
... |
return
...
>>> type(nothing())
<class 'NoneType'>
```
Or, if you wish, you can explicitly return None.
```
>>> def nothing():
... |
return None
...
>>> type(nothing())
<class 'NoneType'>
```
6If you’ve seen void in C++ or Java you have some prior experience with functions that don’t return anything. |
All Python functions return a value, even if that
value is None.
-----
###### What functions can do for us
- Functions allow us to break a program into smaller, more manageable pieces.
- They make the program easier to debug.
- They make it easier for programmers to work in teams.
- Functions can be effi... |
Write a function which calculates the successor of any integer. That
is, given some argument n the function should return n + 1.
2. |
What’s the difference between a formal parameter and an argument?
3. |
When is the body of a function executed?
###### 5.2 A deeper dive into functions
Recall that we define a function using the Python keyword def. |
So, for
example, if we wanted to implement the following mathematical function
in Python:
𝑓(𝑥) = 𝑥[2] −1
Our function would need to take a single argument and return the result
of the calculation.
```
def f(x):
return x ** 2 - 1
```
We refer to f as the name or identifier of the function. |
What follows the
identifier, within parentheses, are the formal parameters of the function.
A function may have zero or more parameters. |
The function above has
one parameter x.[7]
Let’s take a look at a complete Python program in which this function
is defined and then called twice: once with the argument 12 and once
with the argument 5.
7While Python does support optional parameters, we won’t present the syntax
for this here.
-----
Remember: Writi... |
To call the function f()
above, we must supply one argument.
```
y = f(12)
```
This calls the function f(), with the argument 12 and assigns the result
to a variable named y. |
Now what happens?
```
"""
Demonstration of a function
"""
def f(x):
return x ** 2 - 1
if __name__ == '__main__':
```
`y = f(12)` _Here we call the function,_
`print(y)` _supplying 12 as an argument._
```
y = f(5)
print(y)
```
When we call a function with an argument, the argument is passed to
th... |
The formal parameter receives the argument—that is, the
_argument is assigned to the formal parameter. |
So when we pass the ar-_
gument 12 to the function f(), then the first thing that happens is that
the formal parameter x is assigned the argument. |
It’s almost as if we
performed the assignment x = 12 as the first line within the body of the
function.
-----
Once the formal parameter has been assigned the value of the argument,
the function does its work, executing the body of the function.
```
"""
Demonstration of a function
```
`"""` _Now, with x = 12, th... |
Flow of control is returned to the
_point at which the function was called._
```
"""
Demonstration of a function
"""
def f(x):
```
_The function returns the calculated_
```
return x ** 2 - 1
```
_value (143)…_
```
if __name__ == '__main__':
```
`y = f(12)` _So f(12) has evaluated to 143, and_
`print(y)`... |
The signature
of a function is its identifier and formal parameters. |
When we call a
function, the number of arguments must agree with the number of formal
parameters.[8]
8Again, we’re excluding from consideration functions with optional arguments
or keyword arguments.
-----
A function should receive as arguments all of the information it needs
to do its work. |
A function should not depend on variables that exist only
in the outer scope. |
(In most cases, it’s OK for a function to depend on
a constant defined in the outer scope.)
Here’s an example of how things can go wrong if we write a function
which depends on some variable that exists in the outer scope.
```
y = 2
def square(x):
return x ** y
print(square(3)) # prints "9"
y = 3
print(sq... |
prints "27"
```
This is a great way to introduce bugs and cause headaches. |
Better
that the function should use a value passed in as an argument, or a
value assigned within the body of the function (a local variable), or a
literal. |
For example, this is OK:
```
def square(x):
y = 2
return x ** y
```
and this is even better:
```
def square(x):
return x ** 2
```
Now, whenever we supply some particular argument, we’ll always get
the same, correct return value.
###### Functions should be “black boxes”
In most cases functions should... |
A cardinal rule of programming: functions should hide im
-----
_plementation details from the outside world. |
In fact, information hiding_
is considered a fundamental principle of software design.[9]
For example, let’s say I gave you a function which calculates the
square root of any real number greater than zero. |
Should you be required
to understand the internal workings of this function in order to use it
correctly? Of course not! |
Imagine if you had to initialize variables used
internally by this function in order for it to work correctly! |
That would
make our job as programmers much more complicated and error-prone.
Instead, we write functions that take care of their implementation
details internally, without having to rely on code or the existence of
variables outside the function body.
###### 5.3 Passing arguments to a function
What happens when we p... |
When
we call a function and supply an argument, the argument is assigned to
the corresponding formal parameter. |
For example:
```
def f(z):
z = z + 1
return z
x = 5
y = f(x)
print(x) # prints 5
print(y) # prints 6
```
When we called this function supplying x as an argument we assigned
the value x to z. |
It is just as if we wrote z = x. |
This assignment takes
place automatically when we call a function and supply an argument.
If we had two (or more) formal parameters it would be no different.
```
def add(a, b):
return a + b
x = 1
y = 2
print(add(x, y)) # prints 3
```
In this example, we have two formal parameters, a and b, so when we
call ... |
Here we supply x
and y as arguments, so when the function is called Python automatically
makes the assignments a = x and b = y.
It would work similarly if we were to supply literals instead of variables.
9If you’re curious, check out David Parnas’ seminal 1972 article: “On the Criteria
To Be Used in Decomposing System... |
Python always passes arguments by
_assignment. |
Always._
###### 5.4 Scope
Names of formal parameters and any local variables created within a
function have a limited lifetime—they exist only until the function is
done with its work. |
We refer to this as scope.
The most important thing to understand here is that names of formal
parameters and names of local variables we define within a function have
local scope. |
They have a lifetime limited to the execution of the function,
and then those names are gone.
-----
Here’s a trivial example.
```
>>> def foo():
... x = 1
... |
return x
...
>>> y = foo()
>>> y
1
```
The name x within the function foo only exists as long as foo is being
executed. |
Once foo returns the value of x, x is no more.
```
>>> def foo():
... x = 1
... |
return x
...
>>> y = foo()
>>> y
1
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
```
So the name x lives only within the execution of foo. |
In this example,
the scope of x is limited to the function foo.
###### Shadowing
It is, perhaps, unfortunate that Python allows us to use variable names
within a function that exist outside the function. |
This is called shadowing,
and it sometimes leads to confusion.
Here’s an example:
```
>>> def square(x):
... x = x * x
... |
return x
...
>>> x = 5
>>> y = square(x)
>>> y
25
>>> x
5
```
What has happened? Didn’t we set x = x * x? Shouldn’t x also be 25?
No. |
Here we have two different variables with the same name, x. We
have the x in the outer scope, created with the assignment x = 5. |
The x
-----
within the function square is local, within that function. |
Yes, it has the
same name as the x in the outer scope, but it’s a different x.
Generally, it’s not a good idea to shadow variable names in a function.
Python allows it, but this is more a matter of style and avoiding confusion. |
Oftentimes, we rename the variables in our functions, appending
an underscore.
```
>>> def square(x_):
... x_ = x_ * x_
... |
return x_
...
>>> x = 5
>>> y = square(x)
>>> y
25
```
This is one way to avoid shadowing.
Another approach is to give longer, more descriptive names to variables in the outer scope, and leave the shorter or single-character names
to the function. |
Which approach is best depends on context.
###### 5.5 Pure and impure functions
So far, all the functions we’ve written are pure. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.