View on GitHub

python-for-kids

Learning and exercise content on Python for Kids

Day 13 - Function

A function is like an Encyclopeadia. It is there but used only when it is called. Let’s take an example of doing calculations. If you have to do addition then you will use + sign and if you wish you make a fuction you will use the keyword def.

def addition(num1, num2):
    print(num1 + num2)

addition(10,20)

By calling the name addition we can just pass the two values, here 10 and 20 and get the result printed.

Let’s see few more examples,

Simple function

def my_function():
    print("You called me!")

my_function()

With parameter

def my_function2(myname):
    print("Hello from " + myname)

my_function2("Wriju")

Two parameters and return type

def my_function3(firstname, lastname):
    return "Hello from " + firstname + " " + lastname
#passing parameter in exact sequence
print(my_function3("Wriju", "Ghosh"))

#Calling parameter by name
print(my_function3(lastname="Tagore", firstname = "Rabindranath"))

Do nothing function

def my_function4():
    pass

Parameter with default value

When not supplied the default will be used.

def my_function5(myname = "No Name!!!"):
    print("My name is : " + myname)

my_function5("Wrishika")    # call with a parameter value
my_function5()              # call without a parameter value

The code is available.

Day 13 - Exercise

  1. Make function for multiplication and call with different values.

Next: Day 14 - Errors

Back to Index