What are Functions in Python - Explained with Examples for Beginners

Pubblicato il: 05 agosto 2023
sul canale di: 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


In questa pagina del sito puoi guardare il video online What are Functions in Python - Explained with Examples for Beginners della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Pycent com 05 agosto 2023, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 38 volte e gli è piaciuto 2 spettatori. Buona visione!