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
Auf dieser Seite können Sie das Online-Video How To Functions Python From Scratch mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer data science insights 23 Oktober 2022 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 32 Mal angesehen und es wurde von 1 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!