7.1 Creating Functions
In Python, creating functions is a fundamental aspect of programming that allows
your code to be more modular, reusable, and readable. Functions in Python are
defined using the def
keyword, followed by the function name
and parentheses with parameters.
You can always think of a function as a set of commands bundled together and given a name. Here's the general form of a function declaration:
def name(parameters):
command1
command2
commandN
The simplest function in Python might look like this:
def greet():
print("Hello, World!")
You call a function by writing its name with parentheses:
greet() # Outputs: Hello, World!
Calling a function is equivalent to writing its internal code at the point of call. Instead of writing the same code over and over, you can move it into separate blocks and give them a name.
7.2 Passing Arguments to a Function
Working with functions wouldn't be as exciting if they always did the same thing - just a named block of commands. Instead, functions were immediately given parameters - variables through which you can pass different values into the function.
The variables inside a function are called function parameters. And the values that are passed to them during specific call are the function arguments. Function parameters simply receive the values of the arguments.
def greet(name):
print("Hello,", name)
greet("Alice") # Outputs: Hello, Alice!
Example of a function with two arguments:
def print_sum(a, b):
print(f"The sum of {a} and {b} is {a + b}")
print_sum(10, 15) # Outputs: The sum of 10 and 15 is 25
And of course, you can pass entire expressions as arguments:
def print_sum(a, b):
print(f"The sum of {a} and {b} is {a + b}")
print_sum(10*10-123, 15//2) # Outputs: The sum of -23 and 7 is -16
Useful Tip! For C/C++ enthusiasts - all variables in Python are references from the C++ point of view. Function parameters too. When assigning, the value is never copied or duplicated - only the reference is assigned.
7.3 A Function is an Object
In Python, functions are first-class objects, meaning they can be used like any other object. This provides developers with a powerful toolset to create flexible software solutions.
Functions as Objects
As first-class objects, functions in Python can be:
- Assigned to a variable
- Passed as arguments to other functions
- Returned from other functions
- Included in data structures like lists, dictionaries
Examples:
def shout(text):
return text.upper()
yell = shout
def greet(func):
greeting = func("Hello") # calling the function
print(greeting)
greet(shout)
We'll touch on this topic more in the future, but for now, remember — everything in Python is an object. Functions, classes, exceptions, lists, modules - everything.
GO TO FULL VERSION