OKPEDIA PYTHON EN

Defining Functions in Python

In Python, functions are essential building blocks that allow for modular and organized code. To define a function, the "def" keyword is employed.

def function_name (parameters):
# block of instructions
return output_values

In defining a function, the function_name signifies the chosen name for your function. This is followed by parameters, which are a collection of input values that the function can process, neatly enclosed within parentheses.

For clarity and structure, the instructions contained within the function are consistently indented, creating a distinct block of code.

The return statement is used to send back one or more results to the calling program. If no value is being returned, the return statement can be omitted

Examples

Example 1 (Simple Function)

Here, we define a function named `double()` and demonstrate its usage

def double(n):
n=n*2
return n
k=double(5)
print(k)

The output is `10`.

10

The first instruction of the main program is the fourth instruction of the source code:

how the function works

When `double(5)` is called, the number 5 is passed as an argument.

The function processes this input, doubling it, and returns the value 10, which is then stored in the variable `k`.

It's important to note that variables inside a function are termed "local variables". They only exist within the function's scope. On the other hand, variables outside the function, like `k`, are "global variables".

Example 2 (Function with Two Parameters)

This function, `sum()`, takes two parameters:

def sum(a,b)
s=a+b
return s
k=sum(5,2)
print(k)

Call the function with k=sum(5,2)

The output result is

7

Example 3 (Function with Three Parameters)

Here, the `sum()` function is defined to accept three parameters:

def sum(a,b,c)
s=a+b+c
return s
k=sum(5,2,1)
print(k)

Call the function with k=sum(5,2,1)

The output result is 8

8

Example 4 (Returning Multiple Values)

The function `nextprec()` returns two values:

def nextprec(n)
p=n-1
s=n+1
return p,s
prec,next=nextprec(5)
print(prec)
print(next)

Call the function with prec, next = nextprec(5).

In this example, the function returns both the preceding and succeeding values of the input number.

The two values are returned as a tuple, which can be unpacked into individual variables (`prec` and `next_val`).

The result is

4
6

https://how.okpedia.org/es/python/create-function-in-python


Report an error or share a suggestion to enhance this page



FacebookTwitterLinkedinLinkedin