What are Functions in Python - Explained with Examples for Beginners

Veröffentlicht am: 05 August 2023
auf dem Kanal: Pycent com
38
2

Notes prepared by Pycent.com for beginners help and tutorial
*********************
Built-in Functions
Python provides many built-in functions like print(), len(), type(), and others

Example:
Using the built-in len() function to get the length of a list
my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Outputs: 5

User-defined Functions
These are the functions that users create for specific purposes.
Example
def greet(name):
return "Hello, " + name + "!"

print(greet("Alice")) # Outputs: Hello, Alice!


Anonymous (Lambda) Functions
Lambda functions are small, unnamed functions defined using the lambda keyword.
square = lambda x: x * x
print(square(5)) # Outputs: 25

Recursive Functions:
A function that calls itself in order to break down the problem into simpler sub-problems.
Example:
A function that calls itself in order to break down the problem into simpler sub-problems.

Generator Functions
Functions that return an iterator and generate values one at a time using the yield keyword.
Example:


Higher-order Functions
Functions that take one or more functions as arguments and/or return a function as a result
Example:
def apply(func, value):
return func(value)

double = lambda x: x * 2
print(apply(double, 5)) # Outputs: 10

Nested Functions
A function defined inside another function.
Example:
def outer_function(x):
def inner_function(y):
return x + y
return inner_function

result = outer_function(10)
print(result(5)) # Outputs: 15

Functions with Variable-length Arguments (*args and **kwargs)
Functions that can accept any number of positional and keyword arguments.
Example:
def variable_args(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)

variable_args(1, 2, 3, name="Alice", age=25)
Outputs:
Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 25}

Decorator Functions
Functions that wrap another function or a class to extend or modify its behavior without permanently modifying its source code.
Example:
def simple_decorator(func):
def wrapper():
print("Before calling the function")
func()
print("After calling the function")
return wrapper

@simple_decorator
def greet():
print("Hello, world!")

greet()
Outputs:
Before calling the function
Hello, world!
After calling the function


Auf dieser Seite können Sie das Online-Video What are Functions in Python - Explained with Examples for Beginners mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Pycent com 05 August 2023 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 38 Mal angesehen und es wurde von 2 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!