Using Break condition in Python

This article will show a step by step guide on how use Break in Python

In many use cases, or due to certain business rules, we need to exit a loop in any programming language. Or, we need to stop a particular loop and continue with the rest of the code.

This article will help you to understand the use of a break in Python which is mainly used to exit the loops in python programming.

To achieve this we need to use “break” keyword while running a loop.

Let’s take a very simple example of how to use a break in Python programming language.

Example :

j= 1
for i in range (6):
print ('i= ',i, 'j=',j)
if j==32:

Open in new window

If we execute the above code in any Python interpreter, then we will see the following result :

So let’s try to understand the code without adding the break statement.

j= 1
for i in range (6):
print ('i= ',i, 'j=',j)

Open in new window

Now we see the code execute without any break. The loop starts from 1 till 5 as we have provided the range as “6” so starting from 0 till 5 the loop will execute :

If we compare the code with a break keyword, we have given an argument as if the result of “j” will be 32, then end the execution of the code so that the loop will run till range 5, as at this point the result of “j” is “32”.

This article was to explain and show you a simple programme on how to use a break statement in Python. I hope I’ve achieved just that.

Thank you for reading my blog, the reference is taken from one of my article that was published by Experts-Exchange.

Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )


Append row into a CSV file on SFTP

In this post I am going to show how we can append a row into CSV file using simple bash command.

To demonstrate this I am using Linux virtual machine, the OS is on Mint 18.3 64bit.  First me create a sample file on my Linux Machine as like below.

dev@dev-VirtualBox ~/Desktop/CSV $ pwd
dev@dev-VirtualBox ~/Desktop/CSV $ ls
dev@dev-VirtualBox ~/Desktop/CSV $ cat <<EOF >sample.csv
> 1,FIRST_LINE,18-JAN-2018
dev@dev-VirtualBox ~/Desktop/CSV $ ls
dev@dev-VirtualBox ~/Desktop/CSV $

Once the file is created it will look something like below:


Now let us think that this file is on a SFTP server where we need to connect and append another line without renaming or changing the file format.

Login to the server

login as: dev
dev@'s password:
Welcome to Linux Mint 18.3 Sylvia (GNU/Linux 4.10.0-38-generic x86_64)

* Documentation:  <a href=""></a>
Last login: Tue Jan 23 09:55:52 2018 from
dev@dev-VirtualBox ~ $ ls
Desktop  Documents  Downloads  Music  Pictures  Public  Templates  Videos
dev@dev-VirtualBox ~ $ cd Desktop/
dev@dev-VirtualBox ~/Desktop $ ls
dev@dev-VirtualBox ~/Desktop $ cd CSV/
dev@dev-VirtualBox ~/Desktop/CSV $ ls

So now we can login to the server.

Method 1: Now let us execute the below line to insert or append a new row to the existing CSV file i.e. sample.csv:

dev@dev-VirtualBox ~/Desktop/CSV $ sed -i.bak 1i"2,Second_Line,18-JAN-2018" sample.csv
dev@dev-VirtualBox ~/Desktop/CSV $

Once the above line is executed we will see the row is inserted but not at the end but at the beginning.


Now how we can append the line at the end .

dev@dev-VirtualBox ~/Desktop/CSV $ pwd
dev@dev-VirtualBox ~/Desktop/CSV $ ls
dev@dev-VirtualBox ~/Desktop/CSV $ cat sample.csv
dev@dev-VirtualBox ~/Desktop/CSV $ sed -i -e "\$a2,Second_Line,18-JAN-2018" sample.csv
dev@dev-VirtualBox ~/Desktop/CSV $ cat sample.csv
dev@dev-VirtualBox ~/Desktop/CSV $


The line used to insert the row/ append the row at the end is :

sed -i -e "\$a2,Second_Line,18-JAN-2018" sample.csv

Method 2: Now let us check how we can use echo to insert the line at the end.

dev@dev-VirtualBox ~/Desktop/CSV $ echo "3,Third_Line,18-JAN-2018" >> sample.csvdev@dev-VirtualBox ~/Desktop/CSV $ cat sample.csv
dev@dev-VirtualBox ~/Desktop/CSV $

Method 3: Append using a simple python programming

dev@dev-VirtualBox ~/Desktop/CSV $ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('sample.csv', 'a') as file:
...     file.write('4,Fourth_Line,18-JAN-2018')
... ;
   File "<stdin>", line 3
SyntaxError: invalid syntax
>>> with open('sample.csv', 'a') as file:
...     file.write('4,Fourth_Line,18-JAN-2018\n');
>>> exit()

Finally, the file will look like as below:

dev@dev-VirtualBox ~/Desktop/CSV $ cat sample.csv

dev@dev-VirtualBox ~/Desktop/CSV $




To automate the process you can create a script and try to pass the row as a input to the file while calling the script.


Thank you for reading my blog , please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )


Reorder the columns in CSV file using Python

Many time we work on files to load or process the flat files. In this post, I am showing if we receive the file but the columns are not in order then how to rearrange them in the right format. There are multiple ways to handle this but here I am using a simple python code which will reorder my columns.

Say for example my right order of my file should be as below:

 empno, ename, sal 

But say I receive a file with

 sal, ename, empno 


Now here is the simple python script which will change the file into right order :

import csv

with open('file2.csv', 'r') as infile, open('file2_modified.csv', 'a') as outfile:
fieldnames = ['empno','ename','sal']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
for row in csv.DictReader(infile):

Save the above code as “” or anyname you want.

Execute the python script , and check the result.


You can modify the code in various ways as per your need.

Thank you for reading my blog , please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

For and While Loops in Python

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.

In python there are two types of loops: 

  • While loop
  • For loop

When we want to run or execute a piece of code multiple times sequentially, this requires a “for loop”, but there is another alternative called a “while loop”. The while loop can only be used when a specific condition is met, or to execute the code for n number of times—or without having a stop.

The While Loop

Let us try to understand the logic of the while loop. Let’s say a person hits a target using his bow till all the arrows are used up. In this case, as long as the container has an arrow in it, the person will take the arrow and hit the target using his bow.
Let’s assume the number of arrows in the container is 10. The target can be shot as long as the number of arrows is greater than zero. The final step would be to put the bow down when all the arrows have been shot.  So basically, as long as the arrows are present in the container, the loop of hitting the target using the bow will continue.  The logic of the while loop is: as long as the condition is true the loop continues.
Format of while loop in Python:

while <<expression>>:


The while loop starts with the keyword “while” as shown in the above snippet. In the expression, we can use any condition that we want to make it true till we want the loop to be executed—followed by a colon.  Next, there could be one or more statements, but a tab is required before any statement. There is one important thing we need to keep in mind: if in any case the expression never becomes false, then the while loop will never stop, making it an “infinite loop”. In this case, the program will never end.
Now let us convert the example into a proper Python program. 

no_of_arrows = 10
while no_of_arrows > 0 :
	no_of_arrows = no_of_arrows -1
	print ("Number of arrows left in the container" + str(no_of_arrows))
print ("All arrows in the container is over and while loop completed")


Here is the output we get:


============ RESTART: C:/Users/swadhin.ray/Desktop/ ============
Number of arrows left in the container 9
Number of arrows left in the container 8
Number of arrows left in the container 7
Number of arrows left in the container 6
Number of arrows left in the container 5
Number of arrows left in the container 4
Number of arrows left in the container 3
Number of arrows left in the container 2
Number of arrows left in the container 1
Number of arrows left in the container 0
All arrows in the container is over and while loop completed


The Python program automatically determines the end of the “while” when the Python interpreter finds a statement that is not tabbed. We don’t have to explicitly define it.


The For Loop:

When any string or list is iterated in sequence, this requires a for loop.
Here is a simple example to list the letters of a word using a for loop in python.


for x in 'apple':
     print ('Lits of letters in apple :',x)
print ("Apple letter over!")


The result will be as shown below:


============= RESTART: C:/Users/swadhin.ray/Desktop/ =============
Lits of letters in apple : a
Lits of letters in apple : p
Lits of letters in apple : p
Lits of letters in apple : l
Lits of letters in apple : e
Apple letter over!


Now say for example we have a list which has a few names and we want to loop it.

names = ['Ray', 'Mike',  'David']
for j in names:        
   print ( j , ' is a name')

The above code will print the below result or output:


============= RESTART: C:/Users/swadhin.ray/Desktop/ =============
Ray  is a name
Mike  is a name
David  is a name


Thank you for reading my blog , the reference is taken from one of my article that was published by Experts-Exchange.

Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

The Server-Application Interface for Python

In 1993, the web was still in its infancy, with about 14 million users and a hundred websites. Pages were static but there was already a need to produce dynamic content, such as up-to-date news and data. Responding to this, Rob McCool and other contributors implemented the Common Gateway Interface (CGI) in the National Center for Supercomputing Applications (NCSA) HTTPd web server (the forerunner of Apache). This was the first web server that could serve content generated by a separate application.

Since then, the number of users on the Internet has exploded, and dynamic websites have become ubiquitous. When first learning a new language or even first learning to code, developers, soon enough, want to know about how to hook their code into the web.

Python on the Web and the Rise of WSGI

Since the creation of CGI, much has changed. The CGI approach became impractical, as it required the creation of a new process at each request, wasting memory and CPU. Some other low-level approaches emerged, like FastCGI]( (1996) and mod_python (2000), providing different interfaces between Python web frameworks and the web server. As different approaches proliferated, the developer’s choice of framework ended up restricting the choices of web servers and vice versa.

To address this problem, in 2003 Phillip J. Eby proposed PEP-0333, the Python Web Server Gateway Interface (WSGI). The idea was to provide a high-level, universal interface between Python applications and web servers.

In 2003, PEP-3333 updated the WSGI interface to add Python 3 support. Nowadays, almost all Python frameworks use WSGI as a means, if not the only means, to communicate with their web servers. This is howDjango, Flask and many other popular frameworks do it.

This article intends to provide the reader with a glimpse into how WSGI works, and allow the reader to build a simple WSGI application or server. It is not meant to be exhaustive, though, and developers intending to implement production-ready servers or applications should take a more thorough look into the WSGI specification.

The Python WSGI Interface

WSGI specifies simple rules that the server and application must conform to. Let’s start by reviewing this overall pattern.

The Python WSGI server-application interface.

Application Interface

In Python 3.5, the application interfaces goes like this:

def application(environ, start_response):
    body = b'Hello world!\n'
    status = '200 OK'
    headers = [('Content-type', 'text/plain')]
    start_response(status, headers)
    return [body]

In Python 2.7, this interface wouldn’t be much different; the only change would be that the body is represented by a str object, instead of a bytes one.

Though we’ve used a function in this case, any callable will do. The rules for the application object here are:

  • Must be a callable with environ and start_response parameters.
  • Must call the start_response callback before sending the body.
  • Must return an iterable with pieces of the document body.

Another example of an object that satisfies these rules and would produce the same effect is:

class Application:
    def __init__(self, environ, start_response):
        self.environ = environ
        self.start_response = start_response

    def __iter__(self):
        body = b'Hello world!\n'
        status = '200 OK'
        headers = [('Content-type', 'text/plain')]
        self.start_response(status, headers)
        yield body
Server Interface

A WSGI server might interface with this application like this::

def write(chunk):
    '''Write data back to client'''

def send_status(status):
   '''Send HTTP status code'''

def send_headers(headers):
    '''Send HTTP headers'''

def start_response(status, headers):
    '''WSGI start_response callable'''
    return write

# Make request to application
response = application(environ, start_response)
    for chunk in response:
    if hasattr(response, 'close'):

As you may have noticed, the start_response callable returned a write callable that the application may use to send data back to the client, but that was not used by our application code example. This write interface is deprecated, and we can ignore it for now. It will be briefly discussed later in the article.

Another peculiarity of the server’s responsibilities is to call the optional close method on the response iterator, if it exists. As pointed out in Graham Dumpleton’s article here, it is an often-overlooked feature of WSGI. Calling this method, if it exists, allows the application to release any resources that it may still hold.

The Application Callable’s environ Argument

The environ parameter should be a dictionary object. It is used to pass request and server information to the application, much in the same way CGI does. In fact, all CGI environment variables are valid in WSGI and the server should pass all that apply to the ……continue reading…..



Thank you for reading my blog , the reference is taken from one of the article that was published by Leandro Lima on Toptal.

Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

A Python Implementation Comparison

Python is amazing.

Surprisingly, that’s a fairly ambiguous statement. What do I mean by ‘Python’? Do I mean Python the abstractinterface? Do I mean CPython, the common Python implementation (and not to be confused with the similarly named Cython)? Or do I mean something else entirely? Maybe I’m obliquely referring to Jython, or IronPython, or PyPy. Or maybe I’ve really gone off the deep end and I’m talking about RPython or RubyPython (which are very, very different things).

While the technologies mentioned above are commonly-named and commonly-referenced, some of them serve completely different purposes (or, at least, operate in completely different ways).

Throughout my time working with the Python interfaces, I’ve run across tons of these .*ython tools. But not until recently did I take the time to understand what they are, how they work, and why they’re necessary (in their own ways).

In this tutorial, I’ll start from scratch and move through the various Python implementations, concluding with a thorough introduction to PyPy, which I believe is the future of the language.

It all starts with an understanding of what ‘Python’ actually is.

If you have a good understanding for machine code, virtual machines, and the like, feel free to skip ahead.

“Is Python interpreted or compiled?”

This is a common point of confusion for Python beginners.

The first thing to realize when making a comparison is that ‘Python’ is an interface. There’s a specification of what Python should do and how it should behave (as with any interface). And there are multipleimplementations (as with any interface).

The second thing to realize is that ‘interpreted’ and ‘compiled’ are properties of an implementation, not aninterface.

So the question itself isn’t really well-formed.

Is Python interpreted or compiled? The question isn’t really well-formed.

That said, for the most common Python implementation (CPython: written in C, often referred to as simply ‘Python’, and surely what you’re using if you have no idea what I’m talking about), the answer is: interpreted, with some compilation. CPython compiles* Python source code to bytecode, and then interprets this bytecode, executing it as it goes.

* Note: this isn’t ‘compilation’ in the traditional sense of the word. Typically, we’d say that ‘compilation’ is taking a high-level language and converting it to machine code. But it is a ‘compilation’ of sorts.

Let’s look at that answer more closely, as it will help us understand some of the concepts that come up later in the post.

Bytecode vs. Machine Code

It’s very important to understand the difference between bytecode vs. machine code (aka native code), perhaps best illustrated by example:

  • C compiles to machine code, which is then run directly on your processor. Each instruction instructs your CPU to move stuff around.
  • Java compiles to bytecode, which is then run on the Java Virtual Machine (JVM), an abstraction of a computer that executes programs. Each instruction is then handled by the JVM, which interacts with your computer.

In very brief terms: machine code is much faster, but ……continue reading…..



Thank you for reading my blog , the reference is taken from one of the article that was published by Charles Marsh on Toptal. Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

Python Design Patterns

Let’s say it again: Python is a high-level programming language with dynamic typing and dynamic binding. I would describe it as a powerful, high-level dynamic language. Many developers are in love with Python because of its clear syntax, well structured modules and packages, and for its enormous flexibility and range of modern features.

In Python, nothing obliges you to write classes and instantiate objects from them. If you don’t need complex structures in your project, you can just write functions. Even better, you can write a flat script for executing some simple and quick task without structuring the code at all.

At the same time Python is a 100 percent object-oriented language. How’s that? Well, simply put, everything in Python is an object. Functions are objects, first class objects (whatever that means). This fact about functions being objects is important, so please remember it.

So, you can write simple scripts in Python, or just open the Python terminal and execute statements right there (that’s so useful!). But at the same time, you can create complex frameworks, applications, libraries and so on. You can do so much in Python. There are of course a number of limitations, but that’s not the topic of this article.

However, because Python is so powerful and flexible, we need some rules (or patterns) when programming in it. So, let see what patterns are, and how they relate to Python. We will also proceed to implement a few essential Python design patterns.

Why Is Python Good For Patterns?

Any programming language is good for patterns. In fact, patterns should be considered in the context of any given programming language. Both the patterns, language syntax and nature impose limitations on our programming. The limitations that come from the language syntax and language nature (dynamic, functional, object oriented, and the like) can differ, as can the reasons behind their existence. The limitations coming from patterns are there for a reason, they are purposeful. That’s the basic goal of patterns; to tell us how to do something and how not to do it. We’ll speak about patterns, and especially Python design patterns, later.

Python is a dynamic and flexible language. Python design patterns are a great way of harnessing its vast potential.

Python is a dynamic and flexible language. Python design patterns are a great way of harnessing its vast potential.

Python’s philosophy is built on top of the idea of well thought out best practices. Python is a dynamic language (did I already said that?) and as such, already implements, or makes it easy to implement, a number of popular design patterns with a few lines of code. Some design patterns are built into Python, so we use them even without knowing. Other patterns are not needed due of the nature of the language.

For example, Factory is a structural Python design pattern aimed at creating new objects, hiding the instantiation logic from the user. But creation of objects in Python is dynamic by design, so additions like Factory are not necessary. Of course, you are free to implement it if you want to. There might be cases where it would be really useful, but they’re an exception, not the norm.

What is so good about Python’s philosophy?……continue reading…..




Thank you for reading my blog , the reference is taken from one of the article that was published by Andrei Boyanov on Toptal. Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )