How To#functions #python From Scratch
In Python, a function is a group of related statements that performs a specific task. #functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.
Why function is used?
Functions enable programmers to break down or decompose a problem into smaller chunks, each of which performs a particular task. Once a function is created, the details of how it works can almost be forgotten about.
A simple Python function
def fun():
print("Welcome to GFG")
_______________________
#calling a function
def fun():
print("Welcome to GFG")
Driver code to call a function
fun()
---______________________________
*args
sum_integers_args.py
def my_sum(*args):
result = 0
Iterating over the Python args tuple
for x in args:
result += x
return result
print(my_sum(1, 2, 3))
In this example, you’re no longer passing a list to my_sum(). Instead, you’re passing three different positional arguments. my_sum() takes all the parameters that are provided in the input and packs them all into a single iterable object named args.
_______________
**kwargs
Okay, now you’ve understood what *args is for, but what about **kwargs? **kwargs works just like *args, but instead of accepting positional arguments it accepts keyword (or named) arguments. Take the following example:
concatenate.py
def concatenate(**kwargs):
result = ""
Iterating over the Python kwargs dictionary
for arg in kwargs.values():
result += arg
return result
print(concatenate(a="Real", b="Python", c="Is", d="Great", e="!"))
Thank you for reading kindly like and subs
Nesta página do site você pode assistir ao vídeo on-line How To Functions Python From Scratch duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário data science insights 23 Outubro 2022, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 32 vezes e gostou 1 espectadores. Boa visualização!