Sunday, February 3, 2019

What are the functions and procedures in Python

What are the functions and procedures in Python

To manufacture the python program is very complex and has a variety of features, we are required to have mastered and use the functions available in the python program.

If we do not use the function so what?

It will feel later if coding program and we will have a lot of hassle to write the code, because too many code that must be written so that the code would be difficult to read and maintenance.

Advantages Using Functions In Python Program

With the functions on the python program, we can break down the already large program coding into sub-programs simpler. And each feature on the program may be made in one function. when we need a feature, we just call the function only. Later we will try the example programs that I have provided below.

But before that, ....

We should already understand and know the basic theory and what things we need to know about the function in Python.


How to Make Functions in Python Program

Functions in Python, created with the keyword def followed by the name of the function.

Example Code:
fungsi_name def (): 
    print "This Output Function"
Just like any other block of code, we also have to provide spaces or tabs indentation 2 times how to write the contents of the function.

Create a function in Python

Once we create a function, then how?

Once we create a function, we should be able to call like the following code:
fungsi_name ()
For example, try to write the following code:

#Making Function
def greeting (): 
    print "Hay you cool ..
## Calling Function 
greeting ()
Results output:
Hay you cool ..
Calling the function 3 times:
#Making Function
def greeting (): 
    print "Hay you cool ..
##Calling Function
greeting () 
greeting () 
greeting ()
Results output:
Hay you cool .. Hay you cool .. Hay you cool ..
It's easy....

Essentially anything that is in function, when called is what will be done.

FYI: The function can also be invoked in other functions, can even call itself. Function that calls itself, is called a recursive function.
Function Parameters
Now, what if we want to provide input values ​​into a function?

Easy…

We can take advantage of parameters.

What's more the parameter?

The parameter is a variable that holds a value for processing in the function.

Example Code:
def greeting (cool): 
    print (cool)
The coding examples above, we create a function with parameters cool.

So how do I call it?

How calling a function that has a parameter is like the following example:
greeting ( "cool")
"Cool" is the parameter that we provide.

And what if the parameter is more than one?

The way we can do this by using a comma (,) to separate the parameters from each other.

Example Code:
#Make a Function with Parameters
def area_triangle (base,high):
    area=(base * high) / 2
    print "The area of a triangle is:%f"% area
#Calling Functions With Fill in Parameter Value
area_triangle(4,6)


The result:

The area of a triangle is:12.000000

Function To Restore Value

Functions that do not return a value usually called the procedure . But sometimes we need the results of the process of the function to be used in subsequent processes. Then a function must return a value of the processing results or the previous process. How to restore the value is use the keyword return followed by a value or a variable that will be returned.

Example Code:
def area_square (side):
    area = side * side
    return area
# Calling Functions With
print "Square area:% d"% area_square (6)

Results Output:

Square area: 36
What is the difference with the example of the previous coding area_triangle function?

In area_triangle we do print function for the output from the processing directly inside the function. As for area_square function, we do print at the time of function calls. So, area_square function () will be valued in accordance with the results that are returned. So we can use it for subsequent processing.

You can imagine with this assumption:
#formula: side x side 
def area_square (side): 
    area = side * side 
    return spacious 

#formula: side x side x side 
def volume_square (side): 
    volume = area_square (side) * side
In the above example, we are doing the calling function to calculate the volume area_square. When we use the function, then we also need to know the name of the Global and Local variables.

Global variables are variables that can be accessed from all functions, whereas for Local variables can only be accessed within the function where she was alone.

In Programming Python, variable initialization sequence or scope known as LGB (Local, Global, and Build-in). So the python program began looking for local variables in advance, if there is then it is used. But if not there, the search continues to Global, and Build-in. Build-in variables are variables that already exist in Python.

The program Coding example:
#Making MakeVariabelGlobal
name = "FajarYusuf.Com"
version = "1.0.0"
def help ():
    # This is a local variable
    name = "My Python Program"
    version = "1.0.2"
    # access local variables
    print "Name:% s"% name
    print "Version:% s"% version
# access global variables
print "Name:% s"% name
print "Version:% s"% version
# call the help () function
help ()


The result:

What are the functions and procedures in Python

Note that variable names are in the help function () and outside the function `help (). Variable names are in the help function () is a local variable. So when we call the function help () then the value to be shown is the value that is in the function help ().

Why not show that global?

Because as the previous explanation ...

Python will start looking for the start of local to global, and build-in.

If in three places was not found, then it will usually happen NameError or variable is not found.



Example Program with Function

Ok, now it's time we make a python program to function fairly complex. Please create a new file named function_program.py.

And let's start we write the code.

The full code :
#VariabelGlobalTo Save Book Data
book = []
# Function To Display All Data
def show_data ():
    if len(book)<=0:
        print "NO DATA"
    else:
        for index in range (len (book)):
            print "[% d]% s"% (index, book [index])
# Functions for Add Data
def insert_data ():
    new_book = raw_input ("Book Title:")
    book.append (new_book)
# Functions for Edit Data
def edit_data ():
    show_data ()
    index = input ("Input ID book:")
    if (index> len (book)):
        print "ID wrong"
    else:
        title_new = raw_input ("New title:")
        book [index] = title_new
#Function to delete data
def delete_data ():
    show_data ()
    index = input ("Input ID book:")
    if (index> len (book)):
        print "ID wrong"
    else:
        book.remove (book [index])
# Function to Display Menu
def show_menu ():
    print "\n"
    print "----------- MENU ----------"
    print "[1] Show Data"
    print "[2] Insert Data"
    print "[3] Edit Data"
    print "[4] Delete Data"
    print "[5] Exit"
    menu = input ("SELECT MENU>")
    print "\n"
    if menu == 1:
        show_data ()
    elif menu == 2:
        insert_data ()
    elif menu == 3:
        edit_data ()
    elif menu == 4:
        delete_data ()
    elif menu == 5:
        exit ()
    else:
        print "Wrong choice!"
if __name__ == "__main__":
    while (True):
        show_menu ()

Please you try to execute the program and see the results like this:

What are the functions and procedures in Python


Reviewer: FajarYusuf.Com
ItemReviewed: What are the functions and procedures in Python

Seseorang yang ingin membagi pengalaman dan ilmu yang berguna untuk para pembaca FajarYusuf.Com :)

TENTANG SITUS

SITUS INI ADALAH SITUS PEMBELAJARAN PEMROGRAMAN DAN JUGA PEMAHAMAN TERHADAP TEKNOLOGI KOMPUTER. KALIAN BISA MENGIKUTI PEMBELAJARAN PEMROGRAMAN DENGAN BERTAHAP PADA MATERI YANG SUDAH SAYA SEDIAKAN, JIKA ADA MATERI YANG MEMBINGUNGKAN SILAKAN LAKUKAN KOMENTAR PADA MATERI YANG ANDA TANYAKAN ATAU KALIAN BISA MENGHUBUNGI SAYA DIHALAMAN KONTAK.