GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • See All Courses
  • See All Projects
  • See All Articles
  • Python Project Ideas
  • Best Online Learning Platforms
  • Top Coding Apps
  • Best VSCode Extensions for Developers
  • Java Project Ideas
  • Top VSCode Themes
  • Best Linux Distros for Programming
  • Top AI Coding Assistants
  • React Project Ideas
  • Best Python IDEs Compared
  • Top Python Certifications

This view

  • Original page
  • New address

GeezerVison is showing hackr.io — Python Define Function | Docs With Examples

Functions in Python are reusable blocks of code that perform a specific task. They improve code readability, reusability, and organization.

Defining a Function with def

In Python, you define a function using the def keyword:

def greet():
    print("Hello, World!")

Explanation:

  • def is the keyword used to define a function.
  • greet is the function name.
  • The parentheses () can hold parameters (discussed next).
  • The function body is indented and contains the logic to be executed.

Calling a Function

Once a function is defined, call it by using its name followed by parentheses:

greet()

Output:

Hello, World!

Function Parameters

You can pass values to a function using parameters:

def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Alice")

Output:

Hello, Alice!

Explanation: The function takes one parameter, name, and uses an f-string to personalize the greeting.

Default Parameters

You can provide default values for parameters:

def greet_user(name="Guest"):
    print(f"Hello, {name}!")

greet_user()

Output:

Hello, Guest!

Returning Values

Functions can return values using return:

def add(a, b):
    return a + b

result = add(3, 5)
print(result)

Output:

8

Multiple Return Values

Functions can return multiple values as a tuple:

def get_coordinates():
    return 10, 20

x, y = get_coordinates()
print(x, y)

Output:

10 20

Keyword Arguments

You can specify arguments using keywords for clarity:

def introduce(name, age):
    print(f"My name is {name} and I am {age} years old.")

introduce(age=30, name="Bob")

Output:

My name is Bob and I am 30 years old.

Variable-Length Arguments

*args (Multiple Positional Arguments)

Use *args to accept a variable number of arguments:

def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1, 2, 3, 4, 5))

Output:

15

**kwargs (Multiple Keyword Arguments)

Use **kwargs to accept multiple keyword arguments:

def display_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

display_info(name="Alice", age=25, city="New York")

Output:

name: Alice
age: 25
city: New York

Nested Functions

Functions can be defined inside other functions:

def outer_function():
    def inner_function():
        print("This is an inner function.")
    inner_function()

outer_function()

Output:

This is an inner function.

Lambda Functions (Anonymous Functions)

A lambda function is a short function with no name:

square = lambda x: x ** 2
print(square(4))

Output:

16

Key Takeaways

  • Use def to define functions for reusable logic in your Python projects.
  • Functions can accept parameters, return values, and handle flexible arguments.
  • *args allows multiple positional arguments.
  • **kwargs allows multiple keyword arguments.
  • Use lambda functions for short, anonymous operations.

Practice Exercise

Here's a simple challenge, open up your Python editor and try to write a function that takes two numbers and returns their product:

def multiply(a, b):
    return a * b

print(multiply(6, 7))

Wrapping Up

Understanding how to define and use functions is crucial for writing efficient and organized Python code. Functions enhance modularity, making code easier to read and maintain. Happy coding!

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.