Python Basics- loops and functions

Code effortlessly

This post is regarding loops and basic functions in python. Any python programmer should be aware of these concepts.

There is difference between solving a use case and solving it with an elegant code. The word elegant here refers to a code which is simple, less number of lines, properly structured and has high maintainability. The concepts discussed in this post will help you achieve just that.

  1. Loops: Consider a situation where a coder has to repeat a set of code block a number of times, in such cases loops are very efficient. To understand this better let us take an example: we have to print square of first five natural numbers.

One might write:


A bad coder : Although the requirement is fulfilled but if anything changes in requirement (believe me it happens all the time) there will be a huge change that should go into the code.

Another solution could be:

for num in range(5): 

A smart coder: Again the requirement has been achieved with less number of lines. If the problem statement changes to 7 natural numbers, only a single number has to be changed in the code (higher maintainability).In the for loop : num is variable which is iterating over a sequence generated by python built in range function.

Another smart coder: A different approach would be to use a while loop.
Note :-A while loop is preferred when there a need to repeat a section of code an unknown number of times until a specific condition is met. Without a termination condition while loop will run for eternity.

num = 1
while num <=5: # num<=5 is the termination condition
num += 1

2. Functions:

Now, if the problem statement changes and demands that we need the code to be more generic. If there are two users A and B both want to print square of natural number but A wants for 5 and B wants for 10. We cant always change the main code for satisfying the need of different users.
Such a situation demands a use of a function.

def square_n_num(n):
for i in range(n):


Here, we have a defined a function square_n_num which takes a single input or we can say has a single parameter n.

If A wants to print a square of 5 natural number or B to print 10 or C to print 20, all they need to change the parameter while calling the function.

Another example for function could be:

def say_hello(name):
return "Hello {}".format(name)


I hope this post helped you in learning basic concept of loops and functions.

That’s all.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store