Customized Functions

A function is a block where you input values and then you get an output (result). The structure of a function is the following:

def FunctionName(arg1, arg2 , ...):
    [Body]
    ...
 
    return Output

You need to use a valid function name (FunctionName), it's not allowed to call it with number, or with a predefined name. The arguments (arg1, arg2, …) are the inputs of your function, you need to put them a valid name as well. Inside the body you develop your calculations or algorithm. Finally you need to return your output, you do it using a reserved word return.

In python the indentation is a big deal, putting this way, if you are a programmer, it's like a comma in C. So don't forget to use it as well as the colon.

Before to start. I create a file called: myfirtsfunction.py in whichever editor that you prefer (some alternatives here).

Here goes the example.

def sumar(a,b): # input arguments a, b
    c = a + b # the sum is assigned to c
    return c # c is returned

It returns the sum between two numbers:

>>> sumar(3,54)
57

Here goes another example. Let's round a number without using the predefined python function (round).

def roundnum(num):
    num = num + 0.5 # Round the integer part
    num = str(num) # Convert real to string
    index = num.find('.') # Get the index of the period 
    num = num[:index] # Get the integer part as a string yet
    return int(num) # Convert string to integer

Output:

>>> print roundnum(5.6)
6
>>> print roundnum(5.3)
5

Comments

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License