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 )

Using SQL Scripts in Oracle Application Express

Using SQL Scripts we can save all the SQL queries as files that we use very frequently on our database later point of time. This is one of the feature present under SQL Workshop in Oracle Application Express.

How it can be really helpful to use SQL scripts under SQL Workshop?
Let us take an example of any application which is developed using APEX with one form and report. The development team wanted to test it by inserting few records into the form and then viewing the reports. But once the testing is completed the team wanted to clear the data from the base tables and from the reporting tables, logs and other database objects. To achieve this the team can create the delete scripts for each object and execute them on database. This activity can also be used by saving the code into a file within the application so that it can be executed from the application and also be used in future.
In other words it’s a set of SQL commands that are saved into a file as scripts. The file or the script can have more than one SQL commands or it can be a PLSQL block.
Few things we need to keep in mind while using SQL scripts from SQL workshop. 

  • All the SQL Plus commands are ignored in SQL scripts
  • We cannot interact between SQL commands with SQL scripts
  • Bind variables are not supported in SQL scripts
  • We can copy the SQL commands from SQL scripts and run them on SQL Command under SQL workshop

To access SQL Scripts login to your Oracle Application Express.


Now click on “SQL Workshop” option.



Once you see the page as shown in above screen shot you can click on “SQL Scripts” as highlighted .


The above screen shot is the page where we can create any new script or use an existing scripts. This page will show a report where

we can view all the scripts that are created by the current user and if the user is a workshop administrator then it will display

all the scripts created in this workspace. We can also change the view by applying the filters.

The search options (i.e. a magnifying glass shown as above) can be used to search any specific columns or any columns. The view icons will change the view of the reports to display as ICON based reports. The delete option at the right is used to delete any script that we might need to by selecting the check box. The upload button is used to upload any new scripts from our local system to the SQL scripts and create option is used to create any new script.
Creating a new script :
Click on “Create button”.

Once clicked the editor will open as shown below:


Now we can enter the script name but the extension is optional so we will leave as it is. To demonstrate I am using a select statement to select all the records from employee table with name as “Sample_Create_Script”.


Now click on create.


Now we can see our script is created now let us run it. Once you click on run option we will see the below screen.


We can click on Run now option to show the result as below:


From the above page we can see the execution of the SQL statement is completed and the time taken for the execution. Now when we click on the magnifying glass we will see a summary report as shown in below screen:


When wee select the option as “Detail” and click on go we will see the below page as a result.


In this page we have an additional option to edit the existing script, so when we click on edit script it will show the below page.


In the above page we can modify the existing SQL statements and apply the changes by clicking on “Apply Changes”.
To delete an existing SQL Script:
Select the script that you want to delete by selecting the check box as shown in below screen:


Now click on “Delete Checked”. After clicking it will prompt you for confirmation.


Click “OK” .


Now we can see the script is deleted from the application.
We can export or import the scripts by using the export/import option from the Task lists, so we can download them and save to our local system or may utilize them on another workspace. To know how much we can store, we can check the SQL script quotas by clicking on “Show Quotas” option from Tasks.


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 )

Data Mining for Predictive Social Network Analysis

Social networks, in one form or another, have existed since people first began to interact. Indeed, put two or more people together and you have the foundation of a social network. It is therefore no surprise that, in today’s Internet-everywhere world, online social networks have become entirely ubiquitous.

Within this world of online social networks, a particularly fascinating phenomenon of the past decade has been the explosive growth of Twitter, often described as “the SMS of the Internet”. Launched in 2006, Twitter rapidly gained global popularity and has become one of the ten most visited websites in the world. As of May 2015, Twitter boasts 302 million active users who are collectively producing 500 million Tweets per day. And these numbers are continually growing.

Given this enormous volume of social media data, analysts have come to recognize Twitter as a virtual treasure trove of information for data mining, social network analysis, and information for sensing public opinion trends and groundswells of support for (or opposition to) various political and social initiatives. Twitter Trend Topics in particular are becoming increasingly recognized as a valuable proxy for measuring public opinion.

social network analysis and data mining

This article describes the techniques I employed for a proof-of-concept that effectively analyzed Twitter Trend Topics to predict, as a sample test case, regional voting patterns in the 2014 Brazilian presidential election.

The Election

General presidential elections were held in Brazil on October 5, 2014. No candidate received more than 50% of the vote, so a second runoff election was held on October 26th.

In the first round, Dilma Rousseff (Partido dos Trabalhadores) won 41.6% of the vote, ahead of Aécio Neves(Partido da Social Democracia Brasileira) with 33.6%, and Marina Silva (Partido Socialista Brasileiro) with 21.3%. Rousseff and Neves contested the runoff on October 26th with Rousseff being re-elected by a narrow margin, 51.6% to Neves’ 48.4%. The analysis in this article relates specifically to the October 26th runoff election.

Partido dos Trabalhadores (PT) is one of the biggest political parties in Brazil. It is the political party for the current and former presidents, Dilma Roussef and Luis Inacio Lula da Silva. Partido da Social Democracia Brasileira (PSDB) is the political party of the prior president Fernando Henrique Cardoso.

Data Mining and Extracting Twitter Trend Topic Data

I began social media data mining by extracting Twitter Trend Topic data for the 14 Brazilian cities for which data is supplied via the Twitter API, namely: Brasília, Belém, Belo Horizonte, Curitiba, Porto Alegre, Recife, Rio de Janeiro, Salvador, São Paulo, Campinas, Fortaleza, Goiânia, Manaus, and São Luis.

I queried the Twitter REST API to get the top 10 Twitter Trend Topics for these 14 cities in a 20 minute interval (limited by some restrictions that Twitter has on its API). Limiting the query to these 14 cities is done by specifying their Yahoo! GeoPlanet WOEIDs (Where On Earth IDs).

For this proof-of-concept, I used Python and a Twitter library (cleverly called “twitter”) to get all the social network data for the day of the runoff election (Oct 26th), as well as the two days prior (Oct 24th and 25th). For each day, I performed about 70 different queries to help identify the instant trend topics.

Below is an example of the JSON object returned in response to each query (this example was based on a query for data on October 26th at 12:40:00 AM, and only shows the data for Belo Horizonte).

[{"created_at": "2014-10-26T02:32:59Z",
	[{"url": "",
	  "name": "#GolpeNoJN", "query": "%23GolpeNoJN", "promoted_content": null},
	 {"url": "",
	  "name": "#SomosTodosDilma", "query": "%23SomosTodosDilma", "promoted_content": null},
	 {"url": "",
	  "name": "#EAecio45Confirma", "query": "%23EAecio45Confirma", "promoted_content": null},
	 {"url": "",
	  "name": "Uilson", "query": "Uilson", "promoted_content": null},
	 {"url": "",
	  "name": "Lucas Silva", "query": "%22Lucas+Silva%22", "promoted_content": null}, 
	 {"url": "",
	  "name": "Marcelo Oliveira", "query": "%22Marcelo+Oliveira%22", "promoted_content": null},
	 {"url": "",
	  "name": "Cruzeiro", "query": "Cruzeiro", "promoted_content": null},
	 {"url": "",
	  "name": "Tupi", "query": "Tupi", "promoted_content": null},
	 {"url": "",
	  "name": "Real x Bar\u00e7a", "query": "%22Real+x+Bar%C3%A7a%22", "promoted_content": null},
	 {"url": "",
	  "name": "Wanessa", "query": "Wanessa", "promoted_content": null}
  "as_of": "2014-10-26T02:40:03Z",
  "locations": [{"name": "Belo Horizonte", "woeid": 455821}]

Brief Intro to Social Network Analysis

Social Network Theory is the study of how people, organizations, or groups interact with others inside their network. There are three primary types of social networks:

  • Egocentric networks are connected with a single node or individual (e.g., you and all your friends and relatives).
  • Socio-centric networks are closed networks by default. Two commonly-used examples of this type of network are children in a classroom or workers inside an organization.
  • Open system networks are networks where the boundary lines are not clearly defined, which makes this type of network typically the most difficult to study. The type of socio-political network we are analyzing in this article is an example of an open system network.

Social networks are considered complex networks, since they display non-trivial topological features, with patterns of connection between their elements that are neither purely regular nor purely random.

Social network analysis examines the structure of relationships between social entities. These entities are often people, but may also be social groups, political organizations, financial networks, residents of a community, citizens of a country, and so on. The empirical study of networks has played a central role in social science, and many of the mathematical and statistical tools used for studying networks were first developed in sociology.

Establishing the Network

To create a network using the Twitter Trend Topics, I defined the following rules:

  • Each city is a vertex (i.e., node) in the network.
  • If there is at least one common trend topic between two cities, there is an edge (i.e., link) between those cities.
  • Each edge is weighted according to the number of trend topics in common between those two cities (i.e., the more trend topics two cities have in common, the heavier the weight that is attributed to the link between them).

For example, on October 26th, the cities of Fortaleza and Campinas had 11 trend topics in common, so the network for that day includes an edge between Fortaleza and Campinas with a weight of 11:

In addition, to aid the process of weighting the relationships between the cities, I also considered topics that were not related to the election itself (the premise being that cities that share other common priorities and interests may be more inclined to share ……continue reading…..





Thank you for reading my blog , the reference is taken from one of the article that was published by Elder Santos 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 )

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 )

Solve Error: ORA-65096 in 12c

In 12c database when we try to create any user we commonly see the error “Error: ORA-65096” .

We can solve this problem by setting up the undocumented hidden parameter i.e. “_ORACLE_SCRIPT” to true.  In other way we have to user the prefix by adding “C##” or “c##” before the username in container database but by enabling the hidden parameter from logging as SYS user we will be able to create the user without adding the prefix.

Here is a small sample how to create the user when we face error 65096.

SQL*Plus: Release Production on Sun Mar 6 19:04:49 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Enter user-name: sys as sysdba
Enter password:

Connected to:
Oracle Database 12c Enterprise Edition Release - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing opt

SQL>create user sloba identified by ****** ;

Once you hit enter you will see the below error:

<pre>Error starting at line : 1 in command -
create user sloba identified by ******
Error report -
SQL Error: ORA-65096: invalid common user or role name
65096. 00000 -  "invalid common user or role name"
*Cause:    An attempt was made to create a common user or role with a name
           that was not valid for common users or roles.  In addition to
           the usual rules for user and role names, common user and role
           names must start with C## or c## and consist only of ASCII
*Action:   Specify a valid common user or role name.
Error starting at line : 3 in command -


To solve this error enable the hidden parameter to “True”:

SQL>alter session set "_ORACLE_SCRIPT"=true;

Session altered.

SQL>reate user sloba identified by ***** ;

User SLOBA created.

SQL>grant connect , resource to sloba;

Grant succeeded.

Verify by logging into the database with the new user:

SQL*Plus: Release Production on Sun Mar 6 19:04:49 2016

Copyright (c) 1982, 2014, Oracle.  All rights reserved.

Enter user-name: sys as sysdba
Enter password:

Connected to:
Oracle Database 12c Enterprise Edition Release - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing opt

SQL> conn sloba
Enter password:

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 )

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 )