Showing posts with label PYTHON English Version. Show all posts
Showing posts with label PYTHON English Version. Show all posts

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

Tuesday, January 29, 2019

What It's Dictionary In Python Programming

Know What It's Dictionary In Python Programming

At the material then, we've studied the list data structure in python program that is capable of storing a wide range of values ​​that has a variety of data types. List is usually used to store a variety of data collection.

But it turns out, the list has its drawbacks.

Lack of List: the list can not use keywords to access an item or the value. Can only be used by calling the index number only.

But do not worry ya ...

Weakness on the list now can be completed by the Dictionary.

On this matter, we will learn the basic things that should be known about Dictionary in python program.

The following important things:

What is a Dictionary in Python Programming?

Dictionary is a data structure that looks like a dictionary. There is a key word then there the value well. Keyword must be unique (not the same as the others), while the value may be filled with just about anything.

Example Code:
me {
    "name": "FajarYusuf",
    "url": "https://www.fajaryusuf.com"
}


In the example above we are coding to create a Dictionary called me and filled in the name and URL. name and url is the key word (key) that we will use to access the value in it.

This is the difference Dictionary compared with lists and tuples . Dictionary have keywords that can be text, and could also figure, while for lists and tuples only use an index is either a number in order to access its value.

In other programming languages (eg PHP), the Dictionary also known as associative arrays .

make Dictionary

Things that must exist in the manufacture Dictionary is:

  • name Dictionary,
  • Keywords,
  • Value,
  • Open the lid and Dictionary should use curly braces.
Among the key and value must be separated with a colon (:) and when there is more than one item or value, then separated by a comma (,).

Examples of coding an item:
name_dict = {
    "key": "value"
}
Examples of coding of three items:
name_dict = {
    "key1": "value",
    "key2": "value",
    "key3": "value"
}
The contents of the Dictionary can be the following data types:

  • String
  • Integer
  • objects
  • List
  • Tuple
  • Dictionary
  • etc.
Example Code:
FajarYusuf= {
    "name": "FajarYusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
        "facebook": "FajarYusuf",
        "twitter": "@cibinongcreative"
    }
}
Here are the contents of the Dictionary above:
  • name contains the string value "FajarYusuf"
  • age contains an integer with a value 25
  • hobby contains a list of strings
  • get married is boolean True
  • and sosmed contains Dictionary 

using Constructors

In addition to using the above, we also can make the Dictionary of constructor dict () with the parameter keys and values.

Example Code :
color_fruit = dict (orange = "orange", apple = "red", banana = "yellow")
It will generate the dictionary as follows:
{ 'Orange': 'orange', 'apple', 'red', 'banana', 'yellow'}

Accessing Item Values ​​of Dictionary

We already know how to create the Dictionary, now let us learn how to access them.

How to access the same as accessing the list. But the key words used are not numbers, but the keywords we have set in the Dictionary.

Example Code :
#CreateDictionary
fajaryusuf = {
    "name": "Fajar Yusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
    "Facebook": "Fajar Yusuf",
        "twitter": "@cibinongcreative"
    }
}
# Access the contents of the dictionary
print ("My name is %s"% fajaryusuf ["name"])
print ("Twitter: %s"% fajaryusuf ["sosmed"] ["twitter"])


Results output:

What It's Dictionary In Python Programming

In addition to the above manner, we can also access the value Dictionary with method get ().

Example Code:

#CreateDictionary
fajaryusuf= {
    "name": "FajarYusuf",
    "age": 25,
    "hobby": ["coding", "nggame", "ngband"],
    "get married": True,
    "sosmed": {
        "facebook": "FajarYusuf",
        "twitter": "@cibinongcreative"
    } 
}
# Access the contents of the dictionary
print(fajaryusuf.get("name"))
print(fajaryusuf.get("age"))

The result:

Know What It's Dictionary In Python Programming

using Recurrence

To display the output of all the contents of the Dictionary, we can use the loop like this:
# CreateDictionary
web = {
    "name": "FajarYusuf.Com",
    "url": "https://www.fajaryusuf.com",
    "rank": "5"
}
# Print the contents of the dictionary with repetition
for key in web:
    print(web[key])
The result:
Know What It's Dictionary In Python Programming

We can also do it like the following code:
web = {
    "name": "FajarYusuf.Com",https://www.fajaryusuf.com",
    "url": "
    "rank": "1"
}
for key, val in web.items():
    print("%s : %s" % (key, val))
The result:

Know What It's Dictionary In Python Programming

Changing Item Values ​​Dictionary

Dictionary is mutable, which means that its value can be changes as needed. To change the value of the Dictionary, we can do like this coding:

name_dic [ "key"] = "New Value"
Example:

# Making Online Dictionary 
skill = { 
    "key": "Python", 
    "other": [ "CSS", "JAVASCRIPT", "HTML"] 

# Print cartridge skill main 
print (skill [ "key"]) 
# edit any skill The main 
skill [ "key"] = "Ruby" 
# Print the contents of the main skill 
print (skill [ "key"])
The value of key 'key' will be changed from Python to Ruby, he will produce:
Python
Ruby


Removing items from the Dictionary

To remove the value of the Dictionary, we can use the command del and method pop ().

Method pop () is a method that serves to remove items from the dictionary while del function is a function to remove a variable from memory.

Coding example to remove it using del:
>>> del skill["main"]
>>> skill
{'other': ['PHP', 'Java', 'HTML']}

Sample Coding remove by using the method pop ():
>>> skill.pop("main")
'Rust'
>>> skill
{'other': ['PHP', 'Java', 'HTML']}

And if we want to remove all the dictionary at once, we can use the method clear ().

Example Code:
skill.clear()


Adding items to Dictionary

We can use the method update () to add content to Dictionary. Parameters such as Dictionary.

Also serves to add, this method also serves to change the dictionary when the key is inserted are built.

Example Code:
# Create dictionary user
user = {
    "name": "FajarYusuf"
}
# add password
user.update({"password": "P@ssw0rd"})
print(user)
# update name
user.update({"name": "CodingMania"})
print(user)
The result:

{'name': 'FajarYusuf', 'password': 'P@ssw0rd'}
{'name': 'CodingMania', 'password': 'P@ssw0rd'}

Taking the Long Dictionary

To retrieve the amount of data (count) or long-Dictionary, we can use the function len ().

Example Code:
# Make Dictonary 
books = { 
    "python": "Mastering Python within 24 hours", 
    "java": "Tutorial Learning Python for Beginners", 
    "php": "Creating a web application with a CSS" 

# print the amount of data that is in dictionary 
print ( "total book:% d"% len (books))
The result:
total book: 3

Reviewer: FajarYusuf.Com
ItemReviewed: What It's Dictionary In Python Programming

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.