*args and for-else in Python

Amarnath_Bangaru
3 min readMay 25, 2020

args are called non-keyword arguments. It is used when you are not sure or aware of how many arguments will be passed into a function that you created. Let’s see an example,

I created a function ‘adder’ with two positional arguments and when i call the function with four arguments, i encountered a TypeError. Sometimes, there will be cases when you want to specify ’n’ number of arguments on the fly. That’s when you will use *args.

Here you can see how args lets you use any number of arguments as required.

So, *args let’s you pass variable number of non keyword arguments to a function.

Now, let’s talk about for-else block in python. An example is a very good way to learn this,

I will take a simple example first and then a little bit more difficult one for this explanation.

  1. I want to check if the length of a word is divisible by 3 and print something.
For-Else block

The else block never gets executed if ‘break’ statement gets executed. If there is no ‘break’ statement, the else block gets executed anyway as you can see at the bottom of the 3 examples of the above picture. That’s how it is different from if-else block.

2. Calculate LCM of any number of integers passed into a function. This is a combination of *args and for-else.

In the above picture, you can see i wrote a code snub to calculate LCM of any number of integers as I want using a nested loop. Let’s breakdown what’s going on in the background of this program,

The LCM will definitely be a multiple of the largest of the 3 numbers 35,45 and 50. So, i am running a for loop in the range (50,35*45*50) = (50,78750) with a step of 50.

Suppose the multiple takes a value 150 and I want that to be divisible by 35 and 40 for that to become the LCM and after division they will non zero reminders.

The if condition, when it encounters a non-zero reminder, it immediately breaks the inner loop and gives the control to the outer loop where the next multiple is brought into action which is 200.

This process goes on until the if condition doesn’t encounter a non-zero reminder which is for the multiple 3150 and that is when the statements under the inner loop are no longer need to be executed and I created a parallel ‘else’ block where I mentioned ‘break’ to come out of the outer loop too. The ‘else’ block only gets execute when ‘break’ is not evaluated.

If Having no ‘else’ block under ‘if’ is somehow bothering you, we can do this,

As you noticed, since i have used *args to create lcm function, i can pass in any number of numbers and find their LCM.

I am hoping that this explanation has been lucid and easily comprehensible.

AB

--

--

Amarnath_Bangaru

Sharing few things about sql, statistics and product thinking