Member-only story
Python functions: Beginner to Expert
Writing functions in python is a skill acquired over time. In this article, I attempt to write about writing python functions for beginners as well as experts. (If you are new then download it from here: https://www.anaconda.com/products/individual)
Let’s start by a simple task of adding the first 100 positive integers. You might remember the story of how Gauss, the amazing German mathematician, was once asked to add the numbers at age 7! Gauss simply figured out that adding the first 50 numbers with the last 50 numbers(in reverse i.e., 1+100,2+99,3+98, etc) all result in 101; so we end up with 50 pairs of 101’s. Can I write this as a formula? Yes! n(n+1)/2 where n is the list of numbers to add. You can even prove this using induction but I won’t get into it. Let’s implement this in python:
Every user defined function in python starts with “def” followed by the name of the function and optional arguments. return statement is also optional.
Now, suppose you want a function where you can pass multiple arguments but you don’t want to fix the number of arguments in the function itself. That’s when somethings like *args comes to rescue: