You are on page 1of 6

Chapter 8 User-defined function Defining a function with parameters

Defining a function without parameter def functionname(parameter):

def functionname(): statements

statements statements

statements There are 2 types of parameters.

Ex 1) Required parameters:

The number of parameters in the function call must match exactly with the
number of parameters listed in the function definition.

Ex

 a function called superwhat is defined with 1 required parameter


 You have to pass exactly 1 parameter, otherwise it would give a syntax
error:

Ex
Ex Ex

2) Default parameters: Calling a Function

 A default parameter is an parameter that assumes a default value if a Ex


value is not provided in the function call for that parameter.
Code
 if the caller choose to pass a value to this parameter, the parameter will
take the value from the caller first.

Ex

Result
Return from a function Scope of variables:

When we finish the calculation within a function and want to return some result All variables in a program may not be accessible at all locations in that program.
back from the function to the caller or just simply want to get out of a function, This depends on where you have first used that variable.
we can use statement return.
There are two basic scopes of variables in Python:
1) Without sending back value
1) Global variables:
Ex
Global variables are variable that are created outside of any function. This kind of
variables can be used and accessed everywhere in the program body and can be
accessed also by all functions.

Ex

 The statement return doesn’t have to be the last line in the function, you
can put it anywhere.
 The statement return doesn’t have to be the last line in the function, you
can put it anywhere.

2) send back some values

Ex

2) Local variables:

Local variables are variables that are created within a function. Variables that are
defined inside a function body have a local scope which means that local variables
can be accessed only inside the function in which they are first created.
There are 2 possible ways to create (or declare) a new variable within a function

1. Assign a value to a new variable name for the first time in the function

2. Declare it in the parameters list

Global assignment:

A keyword Global is needed if we want to specify some variables inside a function


to have global scope.

Scope of variables: Naming

Names defined inside a def do not clash with variables outside the def, even if the
same names are used elsewhere.

You might also like