Python Functions

In Python, functions are used to group a set of related code together to perform a specific task. Functions are a way of organizing and reusing code, making your programs more efficient and easier to understand.

They allow you to group statements together to perform a specific task, and can be called multiple times with different inputs. In this article, we'll cover the basics of creating and using functions in Python, including defining functions, using default arguments, and assigning functions to variables.

Defining Functions

A function in Python is defined using the def keyword, followed by the function name and a set of parentheses containing any parameters the function takes. The code block for the function is indented after the colon.

1def greet(name): 2 print("Hello, " + name + "!")

In this example, the function is called greet and takes a single parameter, name. When the function is called, it will print a greeting to the specified name.

To call a function, simply use its name and pass any required arguments.

1greet("Max") # Output: "Hello, Max!"

Functions with Return Values

A function in Python can also return a value using the return keyword. This can be useful when you need to use the result of a function in another part of your program.

1def square(x): 2 return x * x

In this example, the function square takes a single parameter, x, and returns the result of x squared.

To use the result of a function with a return value, simply assign the function call to a variable.

1result = square(10) 2print(result) # Output: 100

Functions with Default Arguments

In Python, you can provide default values for function arguments. This allows you to call a function with fewer arguments than it requires, and the missing arguments will use the default value.

1def greet(name, greeting="Hello"): 2 print(greeting + ", " + name + "!")

In this example, the function greet takes two parameters, name and greeting, with a default value of "Hello". If the second argument is not provided, the function will use the default value.

1greet("Max") # Output: "Hello, Alice!" 2greet("Jack", "Hi") # Output: "Hi, Jack!"

Assigning Functions to Variables

In Python, functions can be assigned to variables just like any other value. This can be useful for passing functions as arguments to other functions, or for creating more complex functions on the fly.

1def square(x): 2 return x * x 3 4f = square 5 6result = f(2) 7print(result) # Output: 4

In this example, the function square is assigned to the variable f. This allows f to be called just like square and returns the same result.