Python - 9

Python - 9: Functions

Functions let you group code together and run it whenever you need it.

Your challenge: Create a simple function, call it more than once, then create a function that accepts a value.

✦ Python Editor
▶ Output

Define a function

Use def followed by the function name: def greet():

The indented code underneath belongs to the function.

Call a function

Writing greet() runs the code inside the function.

You can call the same function as many times as you need.

Use parameters

A function can receive information: def welcome(name):

When you call welcome("Alex"), the value "Alex" is stored in name while the function runs.

Try it: Call welcome() with two different names, then create a function that prints a favorite hobby.

Good Python habit: Give functions clear action names such as greet, welcome, or show_score.

👀 Show Example Solution
def greet():
    print("Hello!")

greet()
greet()

def welcome(name):
    print("Welcome " + name)

welcome("Alex")

def favorite_hobby(hobby):
    print("My favorite hobby is " + hobby)

favorite_hobby("Drawing")

Functions make code reusable, while parameters let the same function work with different values.