How To Functions Python From Scratch

Published: 23 October 2022
on channel: 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


On this page of the site you can watch the video online How To Functions Python From Scratch with a duration of hours minute second in good quality, which was uploaded by the user data science insights 23 October 2022, share the link with friends and acquaintances, this video has already been watched 32 times on youtube and it was liked by 1 viewers. Enjoy your viewing!