How To Functions Python From Scratch

Publié le: 23 octobre 2022
sur la chaîne: data science insights
32
1

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


Sur cette page du site, vous pouvez voir la vidéo en ligne How To Functions Python From Scratch durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur data science insights 23 octobre 2022, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 32 fois et il a aimé 1 téléspectateurs. Bon visionnage!