Python for Beginners: Learn to Code from Zero · Lesson 8 of 10

Lesson 8: Functions: Reusable Blocks of Code

Stop repeating yourself. Define functions with def, give them inputs, and get answers back with return.

Lesson 8: Functions: Reusable Blocks of Code

A function is a named block of code you can run whenever you want. You have already used some: print(), len(), range(). Now you will make your own with def.

def greet():
    print("Namaste!")
    print("Welcome to class")

greet()
greet()

Output:

Namaste!
Welcome to class
Namaste!
Welcome to class

Parameters: giving a function information

def greet(name):
    print(f"Namaste, {name}!")

greet("Sita")
greet("Hari")

Output:

Namaste, Sita!
Namaste, Hari!

return: getting an answer back

print() only shows something. return sends a value back so you can store it or use it in more calculations.

def area(length, width):
    return length * width

room = area(12, 9)
print(room)
print(area(3, 4) + area(2, 2))

Output:

108
16

Default values

def price_with_tax(price, rate=13):
    return price + price * rate / 100

print(price_with_tax(1000))
print(price_with_tax(1000, 5))

Output:

1130.0
1050.0

(13% is the usual VAT rate in Nepal; rates can change, so treat it only as an example.)

Variables inside functions

A variable created inside a function exists only there (its scope). Pass information in with parameters and send results out with return, instead of relying on outside variables.

A useful function: grade from marks

def grade(marks):
    if marks >= 80:
        return "Distinction"
    elif marks >= 60:
        return "First division"
    elif marks >= 40:
        return "Pass"
    return "Fail"

for m in [91, 64, 45, 20]:
    print(m, grade(m))

Output:

91 Distinction
64 First division
45 Pass
20 Fail

Try it yourself

  1. Write is_even(n) that returns True or False.
  2. Write average(numbers) for a list of numbers.
  3. Write a function that takes a name and returns it in capital letters with an exclamation mark.

Next lesson: handling errors and working with files.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 8: Functions: Reusable Blocks of Code | MeroSir