Python Function Tutorial
In this tutorial, we explore Python functions, covering built-in, recursive, lambda, and user-defined functions with syntax and examples.
1. Python Function – Objective
In this tutorial, we discussed Python dictionaries. Now, we dive deeper into the language with Python functions. We will cover different types of functions in Python: built-in functions, recursive functions, lambda functions, and user-defined functions with their syntax and examples.
2. Introduction to Functions in Python
A Python function, like in other programming languages, is a sequence of statements grouped together under a name. When the function is called, those statements are executed. This provides code reusability, as you don't have to write the same code multiple times for different data.
3. User-Defined Functions in Python
We'll start by discussing user-defined functions in Python. Python allows you to group a sequence of statements into a function. Functions can have names or be unnamed, as we’ll explore later in this tutorial.
a. Advantages of User-Defined Functions
User-defined functions help break a program into modules, making it easier to manage, debug, and scale. They promote code reuse, and changes to functionality can be made easily. Multiple programmers can also work on different functions.
b. Defining a Function in Python
To define a function in Python, use the def keyword followed by the function name and parentheses, ending with a colon (:).
def hello(): print("Hello")
The body of the function must be indented. You can also add a docstring to explain what the function does.
def hello(): """ This function prints 'Hello' to the screen """ print("Hello")
You can access the docstring using the __doc__ attribute.
print(hello.__doc__)
If you don’t know the content yet, you can use pass to define an empty function.
def hello1(): pass
Functions can also be reassigned.
c. Rules for Naming Functions
Function names must follow the same rules as variable names:
Begin with a letter (A-Z, a-z) or an underscore (_).
Can include letters, digits (0-9), and underscores.
Reserved keywords cannot be used.
It is best to name a function based on what it does.
d. Python Function Parameters
You can pass arguments to a function. Here’s an example of a function that adds two numbers:
def sum(a, b): print(f"{a} + {b} = {a+b}")
If you pass two numbers to the function, it will output their sum.
sum(2, 3) # Output: 2 + 3 = 5
You can also handle different data types like integers and floats, but adding incompatible types will result in an error.
sum(3.0, 2) # Output: 3.0 + 2 = 5.0 sum('Hello', 2) # TypeError
e. Python Return Statement
A function may return a value using the return keyword. Once the return statement is reached, the function stops executing.
def func1(a): if a % 2 == 0: return 0 else: return 1
Calling the function func1(7) returns 1 because 7 is odd.
f. Calling a Python Function
To call a function, simply use its name and pass any necessary arguments.
hello() # Output: Hello
g. Scope and Lifetime of Variables in Python
Variables have scope (visibility) and lifetime (existence in memory) depending on whether they are inside a function (local scope) or outside (global scope).
Local Scope
A variable declared inside a function is only accessible within that function.
def func3(): x = 7 print(x) func3() # Output: 7
Attempting to access x outside the function will result in an error.
Global Scope
A variable declared outside a function has global scope and is accessible throughout the program.
y = 7 def func4(): print(y) func4() # Output: 7
You can modify a global variable from within a function using the global keyword.
def func4(): global y y += 1 print(y) func4() # Output: 8
Lifetime
Variables declared inside functions only exist while the function is running. Once the function ends, the variable is discarded.
def func1(): counter = 0 counter += 1 print(counter) func1() # Output: 1
h. Deleting Python Functions
You can delete a function using the del keyword.
def func7(): print("7") func7() del func7 # Calling func7() now results in an error
4. Python Built-in Functions
Python provides various built-in functions like int(), float(), bin(), hex(), str(), list(), tuple(), and more. Refer to previous lessons for more details on these.
5. Python Lambda Expressions
A lambda function is an anonymous function defined using the lambda keyword. It can take any number of arguments but has only one expression.
myvar = lambda a, b: (a * b) + 2 print(myvar(3, 5)) # Output: 17
6. Python Recursion Function
Recursion occurs when a function calls itself. Here's an example calculating the factorial of a number
def facto(n): if n == 1: return 1 return n * facto(n - 1)
Calling facto(5) returns 120.
7. Conclusion: Python Function
We’ve explored the creation, update, and deletion of functions in Python, along with the use of parameters, return values, scope, and lifetime of variables. Understanding these concepts will allow you to write more efficient and modular code in Python.
Write A Comment
No Comments