MyMisPal
← Python lessons
Lesson 9 of 13

Functions

PYTHON
def vat(amount, rate=0.15):
    return amount * rate

print(vat(1000))
print(vat(1000, 0.05))

def defines a function with its parameters in brackets. return sends the result back to the caller. rate=0.15 is a default used when no value is passed.

PYTHON
def grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    return "C"

for s in [95, 85, 60]:
    print(s, grade(s))
Watch outprint inside a function only shows something; return hands back a value you can store and use. A function without return returns None.

Exercises

Exercise 1

Write net_salary(gross) that returns the salary after a 10% deduction.

Exercise 2

Write is_valid_email(email) returning True if it contains both @ and ., otherwise False.

Spotted a mistake on this page, or have an idea to improve the site?