Python Functions With Examples

Recently, we conducted a session for the New York Python use group, where we discussed Functions in Python. In this tutorial, I will show you Python functions, how to define them, and a few examples of them.

A function in Python is a reusable block of code designed to perform a specific task. It is defined using the def keyword followed by the function name and parentheses (), which can include parameters. For example, def greet(name): creates a function named greet that takes a parameter name and executes the code within its indented body.

What is a Function in Python?

A function in Python is a reusable block of code that performs a specific task. Functions help in breaking down complex problems into smaller, manageable parts. They promote code reusability and make programs more organized and readable.

Define a Function in Python

To define a function in Python, you use the def keyword followed by the function name and parentheses (). Inside the parentheses, you can define parameters that the function can accept. The function body is indented and contains the code to be executed.

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

In this example, greet is a function that takes one parameter name and prints a greeting message.

Call a Python Function

To execute a function, you need to call it by its name followed by parentheses. If the function requires arguments, you pass them inside the parentheses. Here is how to call a function in Python.

greet("Alice")
# Output: Hello, Alice!

Here is the complete example.

def greet(name):
    print(f"Hello, {name}!")
greet("Alice")
# Output: Hello, Alice!

I executed the above Python code, and you can see the output in the screenshot below:

Function in Python

Check out Python Functions vs Methods

Types of Functions in Python

Python supports various types of functions:

  1. Built-in Functions: These are functions that are predefined in Python, such as print()len(), and type().
  2. User-Defined Functions: These are functions created by the user to perform specific tasks.

Python Functions Arguments

Here, I will show you about Python functions arguments.

Default Arguments

You can define default values for function parameters. The default value is used if the caller does not provide a value.

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

greet()
# Output: Hello, Guest!
greet("Alice")
# Output: Hello, Alice!

Check out Python Function Examples with Parameters

Variable-Length Arguments

Python allows you to pass a variable number of arguments to a function using *args for non-keyword arguments and **kwargs for keyword arguments.

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

print(add_numbers(1, 2, 3))
# Output: 6

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

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

Here is the output in the screenshot below:

Python Functions

Check out How to Return Multiple Values from a Function in Python?

Python Functions Examples

Now, let me show you some examples of Python functions.

Example 1: Calculate the Area of a Circle

Suppose you need to calculate the area of a circle given its radius. You can create a function to perform this task.

import math

def calculate_area(radius):
    area = math.pi * (radius ** 2)
    return area

radius = 5
print(f"The area of the circle is: {calculate_area(radius)}")
# Output: The area of the circle is: 78.53981633974483

In this example, calculate_area is a function that takes the radius as an argument and returns the area of the circle.

You can see the output in the screenshot below:

Python Functions With Examples

Example 2: Fetching Weather Data

Consider a scenario where you need to fetch weather data for a specific city. You can create a function to handle this task using an API.

import requests

def get_weather(city):
    api_key = "your_api_key"
    base_url = "http://api.openweathermap.org/data/2.5/weather"
    complete_url = f"{base_url}?q={city}&appid={api_key}"
    
    response = requests.get(complete_url)
    data = response.json()
    
    if data["cod"] != "404":
        main = data["main"]
        weather = data["weather"][0]
        return {
            "temperature": main["temp"],
            "humidity": main["humidity"],
            "description": weather["description"]
        }
    else:
        return "City Not Found"

city = "New York"
weather_data = get_weather(city)
print(f"Weather in {city}: {weather_data}")

In this example, get_weather is a function that fetches weather data for a given city using the OpenWeatherMap API.

Conclusion

In this tutorial, I have explained what a function is in Python, how to define a function in Python and its arguments. I have also explained various Python function examples.

You may also like:

Leave a Comment