Mastery 08 – Creating Functions

As you can see in the previous post, Python gives you many built-in functions like print(), input() etc. But you can also create your own functions.

Definition
A function is a block of code that is used to preform a single task . Functions provide better modularity for your program and a high degree of code reusing.

Creating a function
1. A function begin with the keyword def followed by the function name and parentheses.
2. Arguments are placed within these parentheses and separated with a comma.
3. The code within a function starts after a colon (:) and is indented.
4. A function can return an expression to the caller.
Example:
def sayHello(name):
    print("Hello", name)

Can you have more than one function with the same name? Yes! but….
You can have more than one function with the same name (this called Function Overloading), but can only use the latest defined function.

def sayHello(firstName):
    print("Hello", firstName)
def sayHello(firstName, lastName):
    print("Hello", firstName, lastName)


sayHello("Tomer", "Lieber") – this line will call the second function.
But,
sayHello("Tomer") – this line will produce an error because the latest defined sayHello function takes two arguments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: