0% found this document useful (0 votes)
18 views

4 Functions

Functions allow programmers to organize code and reuse functionality. There are two types: void functions perform actions but don't return values, while fruitful functions return values. Built-in functions like len() and random() are pre-defined, while user-defined functions are created using def. Functions are called by name and pass arguments, which become parameters available inside the function. This allows breaking large programs into smaller, more manageable pieces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

4 Functions

Functions allow programmers to organize code and reuse functionality. There are two types: void functions perform actions but don't return values, while fruitful functions return values. Built-in functions like len() and random() are pre-defined, while user-defined functions are created using def. Functions are called by name and pass arguments, which become parameters available inside the function. This allows breaking large programs into smaller, more manageable pieces.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Functions

Function calls
• In the context of programming, a function is a named sequence of
statements that performs a computation.

• The name of the function is type. The expression in parentheses is


called the argument of the function. The argument is a value or
variable that we are passing into the function as input to the
function.
• It is common to say that a function “takes” an argument and
“returns” a result. The result is called the return value.
Built-in functions
• Python provides a number of important built-in functions that we
can use without needing to provide the function definition.
• The max and min functions give us the largest and smallest values in
a list, respectively:
Built-in functions
• Another very common built-in function is the len function which tells
us how many items are in its argument. If the argument to len is a
string, it returns the number of characters in the string.

• You should treat the names of built-in functions as reserved words


(i.e., avoid using “max” as a variable name).
Type conversion functions
• Python also provides built-in functions that convert values from one
type to another. The int function takes any value and converts it to
an integer, if it can, or complains otherwise:
Type conversion functions
• Float converts integers and strings to floating-point numbers:

• Finally, str converts its argument to a string:


Random numbers
• Given the same inputs, most computer programs generate the same
outputs every time, so they are said to be deterministic. For some
applications, though, we want the computer to be unpredictable.
Games are an obvious example, but there are more.
• There are ways to make it at least seem nondeterministic. One of
them is to use algorithms that generate pseudorandom numbers.
Pseudorandom numbers are not truly random because they are
generated by a deterministic computation, but just by looking at the
numbers it is all but impossible to distinguish them from random.
Random numbers
• The random module provides functions that generate pseudorandom
numbers.
• The function random returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0). Each time you call random, you get the
next number in a long series.
Random numbers
• The function randint takes the parameters low and high, and returns
an integer between low and high (including both).

• To choose an element from a sequence at random, you can use


choice:
Math functions
• Python has a math module that provides most of the familiar
mathematical functions. Before we can use the module, we have to
import it:

• This statement creates a module object named math. If you print the
module object, you get some information about it:
Math functions
• The module object contains the functions and variables defined in
the module. To access one of the functions, you have to specify the
name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
Math functions
• The first example computes the logarithm base 10 of the signal-to-
noise ratio. The math module also provides a function called log that
computes logarithms base e.
• The second example finds the sine of radians. The name of the
variable is a hint that sin and the other trigonometric functions (cos,
tan, etc.) take arguments in radians.
Math functions
• To convert from degrees to radians, divide by 360 and multiply by 2𝜋:

• The expression math.pi gets the variable pi from the math module. If
you know your trigonometry, you can check the previous result by
comparing it to the square root of two divided by two:
Adding new functions
• It is also possible to add new functions. A function definition
specifies the name of a new function and the sequence of
statements that execute when the function is called.
• Once we define a function, we can reuse the function over and over
throughout our program.
Adding new functions
• def is a keyword that indicates that this is a function definition. The
name of the function is print_lyrics.
• The rules for function names are the same as for variable names:
letters, numbers and some punctuation marks are legal, but the first
character can’t be a number. You can’t use a keyword as the name of
a function, and you should avoid having a variable and a function
with the same name.
• The empty parentheses after the name indicate that this function
doesn’t take any arguments.
Adding new functions
• The first line of the function definition is called the header; the rest is
called the body. The header has to end with a colon and the body
has to be indented.
• The body can contain any number of statements.
• The strings in the print statements are enclosed in quotes. Single
quotes and double quotes do the same thing; most people use single
quotes except in cases like this where a single quote (which is also an
apostrophe) appears in the string.
Adding new functions
• Defining a function creates a variable with the same name.

• The value of print_lyrics is a function object, which has type


“function”. The syntax for calling the new function is the same as for
built-in functions:
Adding new functions
• Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could write
a function called repeat_lyrics:
Definitions and uses
• Function definitions get executed just like other statements, but the
effect is to create function objects. The statements inside the
function do not get executed until the function is called, and the
function definition generates no output.
• As you might expect, you have to create a function before you can
execute it. In other words, the function definition has to be executed
before the first time it is called.
Flow of execution
• In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
• Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
Flow of execution
• A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of the
function, executes all the statements there, and then comes back to
pick up where it left off.
• While in the middle of one function, the program might have to
execute the statements in another function. But while executing that
new function, the program might have to execute yet another
function.
• When you read a program, you don’t always want to read from top to
bottom. It makes more sense if you follow the flow of execution.
Parameters and arguments
• Some of the built-in functions we have seen require arguments. For
example, when you call math.sin you pass a number as an argument.
Some functions take more than one argument: math.pow takes two,
the base and the exponent.
• Inside the function, the arguments are assigned to variables called
parameters.
Parameters and arguments
• This function assigns the
argument to a parameter
named bruce. When the
function is called, it prints the
value of the parameter
(whatever it is) twice.
• This function works with any
value that can be printed.
Parameters and arguments

• The argument is evaluated before the function is called, so in the


examples the expressions “Spam ’*4andmath.cos(math.pi)‘ are only
evaluated once. You can also use a variable as an argument:
Fruitful functions and void functions
• Some of the functions we are using, such as the math functions, yield
results; they are called fruitful functions. Other functions, like
print_twice, perform an action but don’t return a value. They are
called void functions.
• When you call a fruitful function, you almost always want to do
something with the result; for example, you might assign it to a
variable or use it as part of an expression:
Fruitful functions and void functions
• Void functions might display something on the screen or have some
other effect, but they don’t have a return value. If you try to assign
the result to a variable, you get a special value called None.

• The value None is not the same as the string “None”. It is a special
value that has its own type.
Fruitful functions and void functions
• To return a result from a function, we use the return statement in
our function. For example, we could make a very simple function
called addtwo that adds two numbers together and returns a result.

• When this script executes, the print statement will print out “8”
because the addtwo function was called with 3 and 5 as arguments.
Why functions?
• Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read, understand,
and debug.
• Functions can make a program smaller by eliminating repetitive code.
Later, if you make a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts
one at a time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once
you write and debug one, you can reuse it.
Exercises
• Exercise 4.1 - Rewrite your pay computation with time-and-a-half for
overtime and create a function called computepay which takes two
parameters (hours and rate).
• Exercise 4.2 - Rewrite the grade program from the previous chapter
using a function called computegrade that takes a score as its
parameter and returns a grade as a string.
Exercises
• Exercise 4.3 - Rewrite the triangle program using a function called
triangle that takes the length of the 3 sides of a triangle as its
parameters and returns its type (equilateral, isosceles or scalene).

You might also like