Home » Learn Python » Functions » Introduction to Python Functions

Introduction to Python Functions

A function in programming is a block of code that you can run when you want, usually via its name.

You can think of functions as like “black boxes”: you can pass data to a function (“function arguments“) and you can get data out of a function (“return values“). The function can process the data.

However, a function may also neither accept arguments nor return anything.

Making a function actually run is called calling the function.

# Define a function called "greeting"
def greeting():
    print("Hello")

# Call the function
greeting()
Hello

Function Parameters

You can pass data to a function using parameters and arguments. One or more variables are listed in the function () brackets; these are called parameters. The values that you pass to the function are then arguments.

The round function brackets are a bit like a chute that you throw data down. The data appears in the function parameters, at the bottom of the chute.

# Define a function called "greeting"
# that accepts two arguments.
def greeting(name, age):
    print(f"Hello {name}. You are {age} years old.")

# Call the function
greeting("Bob", 30)
Hello Bob. You are 30 years old.

Return Values

A function can return a value with the return keyword.

# A function with a return value
def get_user_name():
    name = input("Enter your name: ")
    return name

# Call the function and obtain the return value
user_name = get_user_name()

print("User name: ", user_name)
Enter your name: Bob
User name:  Bob

Multiple Return Values

It’s easy to return multiple values from a Python function, using tuples.

# A function with multiple return values
def get_user_details():
    name = input("Enter your name: ")
    age = input("Enter your age: ")
    return (name, age)

# Call the function and obtain the return values
(name, age) = get_user_details()

print(f"Your name is '{name}' and your age is '{age}'")
Enter your name: Bob
Enter your age: 25
Your name is 'Bob' and your age is '25'

Leave a Reply

Blog at WordPress.com.

%d