Oct. 01, 2012

Functions in Python

Functions

Please see the Functions Cheat Sheet for the most updated version:

http://www.pythonforbeginners.com/python-functions-cheat-sheet/

Why functions?

Reduce code tasks into simples tasks

Can easier split up the code between developers

Elimination of duplicate code

Reuse code

Get a good structure of the code

Easier debugging.

How do I create a function?

Must be defined before it's used. 

The function blocks begin with the keyword def followed by the function name and
parentheses. 

The function has to be named plus specify what parameter it has. 

A function can use a number of arguments. Every argument is responding to a
parameter in the function. 

The function often ends by returning a value using return. 

Small Example

Let's demonstrate how this works. 

Here we create a function by using the keyword "def" followed by the functions
name "name" and the parentheses (). 

We indent the code and write what we want to accomplish in the function. 

This function will just ask for the users name using the raw_input function
and then return the value. 

The script is "called" by simple typing the name of the function >> name()
def name():
    # Get the user's name.
    name = raw_input('Enter your name: ')
  
    # Return the name.
    return name

name()
More Reading
http://python.org/

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.