Basics of Python – Part 2

Start with Basics of Python – Part 1

Dot Notation

Using dot notation with strings.
Let us consider an example where we convert the string to upper case using dot notation.

>>> mysore = “The city is awesome !”

>>> print len(mysore)
>>> print mysore.upper()

Printing strings

>>> print(“This String”)

Printing Variables

>>> Stone_cold = “Stunner”
>>> print(Stone_cold)

Concatenation

Combining strings together is called concatenation . The + operator combine the strings.

>>> print “Indian “+ “Air ” +”Force ”

The space after the word is to make the string look like sentence.

String Conversion

The str() method converts non-strings into strings.

>>> print “Sourav Ganguly scored “+ str(100) + “on his Test Debut”

String Formatting

The % operator after a string combines a string with variables. The % operator will replace  %s in the string with the string variable.

Example 1:
>>> string_1 = “Sourav”
>>> string_2 = “Dada”

>>> print “Indian captain %s is also called as %s.” % (string_1, string_2)

Example 2:

>>> batsman = raw_input(“Who is the batsman?”)
>>> captain = raw_input(“Who is the captain?”)
>>> series = raw_input(“Which series did he win for India?”)

>>> print “The Indian %s and %s Sourav Ganguly won %s series for India.” % (batsman, captain, series)

Date and Time 

We can import datetime function from datetime module.

>>> from datetime import datetime

Current Date and Time

Here is the code to print current date and time.

>>> from datetime import datetime
>>> now = datetime.now()
>>> print datetime.now()

Control Flow

The ability to choose from different situations based on what’s happening in the program.

>>> x = int(input(“Please enter an integer: “))

Please enter an integer: 35

>>> if x < 0:

…     x = 0

…     print(‘Negative changed to zero’)

… elif x == 0:

…     print(‘Zero’)

… elif x == 1:

…     print(‘Single’)

… else:

…     print(‘More’)

if statements, for statements, range fuction, break and continue, else clause loops, pass statements are few of the control flow statements.

Comparators

Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)

Boolean Operators

AND 

OR 

NOT

Conditional Syntax

The statements used for decision making are called conditional statements.

if condition_1:

statement_block_1

elif condition_2:

statement_block_2

else:

statement_block_3

This post concludes basics of python.

Basics of Python – Part 1

Download the python interpreter from this link . Choose either 3.0 or 2.0 version depending upon your compatibility. In this exercise version 2.0 was used for examples. Based on the current and future trends I would recommend 3.0.

Now let us look into some basic concepts in python programming language.

Variables:

As with most programming languages, assigning a value for a variable is as simple as:
a = 10

Booleans:

The two switch states True or False can be assigned to a variable.
a = True
(or)
a = False

Reassigning variable values:

A variable b = 10 can be given a value as b = 5 in the next line, and the value can be printed using
print b

Indentation:

Indentation is one of the most important aspect of python, either use a Tab space or 4 white spaces but not both. Here’s an example of a simple python function.

def example()
var = 15
return var
print example()

Single-line Comment:

Use # at the beginning of a line to give a single line comment.
# This is a single line comment in python.

Multi-line Comments:

If the comment is more than one line use double inverted comma’s thrice at the start and end of the comment.
“”” This is a multi-line
comment”””

Basic Math Operations:

All basic math operations such as addition(+), subtraction(-), multiplication(*) and division(%) can be performed similar to other programming languages.
>>print 36 + 64
100
>>print 200 – 100
100
>>print 10 * 10
100
>>print 1000 / 10
100

Exponentiation:

In python, the function of exponential can be performed using ** keys.
>> chairs = 10 ** 2
>> print chairs
100

Modulo:

Modulo operation can be performed using %.

Strings:

Assigning strings values and printing them.
python = “Hello world!”
print(“python”)

Escaping characters:

In python both single quotes and double quotes can be used for commenting. When using single quote, the interpreter doesn’t understands the code. In such cases we can use escape characters such as backslash(\).
‘Isn\’t it the python?’

Accessing by Index:

We can access any character of a string by indexing. Indexing starts from 0.
>>sixth_letter = “python”[5]
>>print sixth_letter
n

String methods:

We can calculate length of the string using len()
>>python = “Indian”
>>len(python)
>>print len(python)
6

We can convert lower case string to upper case string
>>python = “indian”
>>”indian”.upper()
>>print python.upper()
INDIAN

We can convert upper case string to lower case string
>>python = “INDIAN”
>>”INDIAN”.lower()
>>print python.lower()
indian

We can convert a variable to a string
>>pi = 3.14
>>print str(pi)
3.14

So, this concludes basics of python part-1.

Understanding Apache Spark

In my last blog post I had discussed about data, now let us understand a modern tool to process huge datasets(BigData) so as to extract insights from data.

Apache Spark – A fast and general engine for large-scale data processing. Spark is a more sophisticated version of data processing engine compared to engines using MapReduce model.

One of the key feature with Apache Spark is Resilient distributed datasets(RDD’s). These are data structures available in Spark.

Spark can run on Hadoop YARN cluster. The biggest advantage to keep large datasets in memory adds to the capability of Spark over MapReduce.

Applications types that find Spark’s processing model helpful are:

  1. Iterative algorithms
  2. Interactive analysis

Other areas which make Spark more adoptable are:

Spark DAG(Directed Acyclic Graph) – This component of the engine helps to convert variable number of operations into a single job.

User Experience – Spark makes user experience smooth by having a plethora of API’s to perform data processing tasks.

Spark has API’s in these languages: Scala, Java, Python and R.

Spark programming comprising of the Spark shell(also known as Spark CLI or Spark REPL) makes it simple to work on datasets. REPL stands for read-eval-print loop.

Spark on the other hand provides modules for:

  1. Machine learning(MLib) – Provides a framework for distributed machine learning.
  2. Graph processing(Graphx) – Provides a framework for distributed graph processing.
  3. Stream processing(Spark Streaming) – Helpful for streaming(real-time) analytics. Data ingestion takes place in mini-batches and RDD transformations are performed upon these mini-batches.
  4. SQL(Spark SQL) – Provides data abstraction known as SchemaRDD which supports structured and semi-structured data.

These components operate on Spark core. Spark core provides platform for in memory computing and referencing datasets in external storage systems.

Companies that are using Apache Spark – Google, Facebook, Twitter, Amazon, Oracle, et al.

Spark services are provided on notable cloud platforms such as Google Cloud Platform(GCP), Amazon Web Services(AWS) and Microsoft Azure.

Source: Apache Spark

 

Data: The new “OIL” of Information Era

Dataoil

Anything and everything that can be produced, which we can quantify is referred as data. In simple words granular information is data. Automobiles and machinery have been running on oil extracted from earth. In the Internet age devices, machines and all mundane activities shall be driven by data.

All data that exists can be classified into three forms:

  1. Structured Data
  2. Semi-structured Data
  3. Unstructured Data

Structured Data – Structured data is a standardized format for providing information. Examples: Sensor data, machine generated data, etc.

Semi-structured Data – Semi structured Data does not exist in standard form but can be used to derive structured form with little effort. Examples: JSON, XML, etc.

Unstructured Data – Unstructured Data is any data that is not organized but may contain data which can be extracted. Examples: Social media data, Human languages, etc.

Most global tech giants operate from data generated by their users. Google, Amazon, Facebook, Uber, et al. come under the same umbrella. The insights derived from structured and semi structured data can help us in decision making. The magnitude and scale at which these companies generate data is astounding.

Databases play a very important role in storing data. But traditional databases are no longer a choice to store data in today’s fast moving world. New age file systems and infrastructure have started operating to cater the demands of ever expanding Internet space.

In the human world, the voice, speech, text, walking speed, everything can be classified as unstructured data, since we can derive a lot of insights from them. A mobile device per individual is pretty much sufficient to analyse the behavior of a sizable population in a region.

Data collected from a population for a relatively considerable time can be used to derive patterns about the population. Hence, data is the driving force which will fuel innovation and economy from here.

Bengaluru and the spirit of Entrepreneurship

Here is a list of reasons for Bengaluru being a favorite location to start-up:

1 – Technology Infrastructure :- High end systems, high speed internet, ask for anything new in the field of technology, it’s usually first implemented in Bengaluru. That gets Bengaluru a premium tag.

2 – Workforce & Talent :- A plethora of highly qualified professionals makes it a easy choice for most of the entrepreneur’s to choose Bengaluru to kick-start their venture. Engineer’s and Business professionals are a new class of the neatly woven fabric in Bengaluru.

3 – Geographic location :- Weather in Bengaluru is usually pleasant with room temperature hovering between 23°C to 27°C throughout the year with summer being an exception. Bengaluru is the king among metropolitan cities of India, when it comes to weather.

4 – Koramangala :- The Heart of Entrepreneurship for the whole nation is located at koramangala. Visit any street in this locality of Bengaluru and you shall encounter a new venture or business being built. Koramangala is a place that every entrepreneur must visit at-least once in their lifetime.

5 – Government support :- The Karnataka Government has been one of the most proactive government in the country as far as Entrepreneurship is considered. Some of the highly successful Information Technology & Bio-technology ventures started off from Bengaluru by the initial support offered by Karnataka Government. ITPL and many SEZ’s in the city are examples for it.

6 – Cosmopolitan Nature :- This is the ultimate reason for Entrepreneurship to be cherished in Bengaluru. People from different parts of the country live and work in Bengaluru, surely Bengaluru is a “Melting pot”.

7 – Cost of living :- Of late the costs have been going up in Bengaluru considering inflation and other factors. But it’s still affordable for middle class to survive. Cost of living is comparatively cheaper than Delhi and Mumbai.

8 – Education :- The city hosts a series of exceptional institutions, IISc and IIM being the cream. Even at secondary and higher secondary level there are many noteworthy institutions.

9 – Law and Order :- Law & order is usually stable with few huff and puff at times. Law & order is one more reason to choose Bengaluru as a business location.

10 – Healthcare :- Many healthcare bodies are spread-out through the city, there are specialized units in the city where foreigner’s are addressed too. Healthcare facilities are cheaper in Bengaluru compared to International standards.

Bengaluru is the first Indian city to have it’s own logo.

BE”ngalur“U”, BE and U in Bengaluru stands for “Be You”.

Google Analytics for MOHANMA.COM : Launch(26th Jan) to 2nd March

Firstly, thanks to everyone who have visited mohanma.com. The above image shows the global footprint of mohanma.com.

The total number of sessions so far has been 563. India leads in web traffic with 493 sessions. Followed by United States of America, Australia and United Kingdom. Traffic has been flowing in from different parts of Europe, Canada, Peru, China, Japan, etc as well.

To be frank, I have been surprised with the kind of response that mohanma.com has been receiving from day 1. Thanks to all the readers, well-wishers who have been pouring in their feedback via WhatsApp, Facebook and the comments section on website.

Love,

Mohan M A

Difference between Process and Thread in Java

 

ProcessThread
1) Part of Concurrent Programming.1) Integral part of Concurrent Programming.
2) A process has a self-contained execution environment. 2) A thread is a lightweight process.
3) Process has its own memory space.3) Threads share the process's resources, including memory and open files.
4) Processes are synonymous with programs or applications.4) Threads do things such as memory management and signal handling.
5) A Java application can create additional processes using a ProcessBuilder object.5) A Main thread has the ability to create additional threads.
6) To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets.6) Threads exist within a process. This makes for efficient, but potentially problematic, communication.

Processing time for a single core is shared among processes and threads through an OS feature called time slicing.

Time Slice or Preemption : A technique to implement multitasking in operating systems. The period of time for which a process is allowed to run in a preemptive multitasking system is generally called the time slice or quantum. The scheduler is run once every time slice to choose the next process to run.

Source: 1) The Java™ Tutorials
        2) Wikipedia

Object-Oriented Programming (OOP)

OOP is based on “objects“. An object can perform a set of functions. The functions that the object performs defines the object’s behavior.

For example, the Batsman(object) can play shots or a Bowler(object) can Bowl.

Languages that support object-oriented programming have four important aspects:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

Abstraction involves the process to define objects that represent abstract actions which can perform work,
report on and change their state, and interact with other objects in the system.

Encapsulation is the process of enclosing data and functions into a single element.

Inheritance is when an object or class is based on another object,
using parent objects properties to maintain the same behavior in the child object.

Polymorphism is the method of having a single interface to objects of different types.

Object-oriented programming (OOP) is a programming paradigm

Objects — > data — > fields — > attributes — > methods(code)

Some of the popular languages that support Object-Oriented Programming

Java, Python, C++, C#, Perl, Ruby , Objective-C, PHP, et al.

Why I chose India ? ‘The perquisite of choosing India over America’

Just like any other kid who completes engineering, I too had plans of pursuing masters in America.

I had the test scores of GRE and TOEFL, got few letters of recommendation, got all my transcripts. I was at the verge of applying to universities in US.

Initially, I had plans of joining masters program in Spring 2012(as I completed my Engineering in 2011). But postponed the joining date to Fall 2012 as the number of universities offering masters course would be more in Fall 2012.

I was fascinated with the idea of working with/studying cutting edge technologies in US.

When I started my engineering in 2007, the head of physics department professor H N Sathyamurthy  had introduced me to the concept of higher education in US(before recession 2008), where there was plethora of opportunities if you worked hard. I am thankful to him for inculcating such ideals.

So the thought of going over to US was a prolonged one given the time period between ideation and pursuing masters.

Fast forward December 2011, I had two choices, either go over to US for masters or stay back in India with a comfortable lifestyle. The stakes were high if I was going over to US, the opportunity was a gamble.

I chose staying back in India. I was complacent initially, for not chasing the american dream.

But 3-6 years down the line I have realized the essence and advantage of staying back in India.

The biggest advantage of staying back has been the fact that you can be for your family and vice-versa.

A lot of technological advancements that used to be limited to US and developed countries have started making their presence in India as well. Cutting edge technology and premier research work is now available in different metro cities of India. Maybe not full fledged, but they have started having a decent visibility.

Given today’s political and visa norms in US, I find it was a very good decision to stay back in India.

Also, the kind of tech atmosphere that India is offering today can be contemplated to be among the best in the world.

When it comes to Internet startups, US has started reaching it’s saturation point. India offers a level playground and equal opportunity with net neutrality for tech startups.

The crowd in India is open to new ideas which was not the case say about 8-10 years ago.

Food – being a gourmet I find myself fortunate to eat as much Indian dishes as possible.

Healthcare – way cheaper compared to US even for a small ailment such as common cold.

The grass is always greener on the other side. It would be naive of me if I had believed only in “American Dream”.

How and What I learnt being an Entrepreneur ?

It all started with the iAccelerator program of IIM-Ahmedabad in 2010, when most of my batch-mates and peers were busy preparing for semester exams, I was at IIIT-Bangalore pitching my first startup plan.

Please find the screenshot of feedback I am sharing below.

Even-though my pitch couldn’t make it that year, the sense of clearing the application round and being invited to IIIT-B in itself was a big boosting success for me.

This was at a time when startup was not a buzzword in India(pre smartphone era), startups in India had just started keeping their baby steps.

I am a first generation Entrepreneur.

Initially entrepreneurship was just an attraction(2009-sophomore year), I remember there was a delegate who was in our college as part of student interaction program from USA, he was explaining a hall of 100-150 students about the trends in US where students dropout to start their own website/company(Facebook was 5 year old startup at this point). I had announced to the hall and him saying “you got it mate, I will have a website” with lots of adrenaline rush.

Professors in my college were very supportive at this stage, I have discussed a lot of my ideas with professor Pushpalatha K N(Linear Integrated Circuits and Applications) who was always encouraging me. Also, professor Deepa N P(micro-controllers) was keen on helping me setting up a web portal way back in 2009. And not to forget professor Nirmal Kumar Benni whom I could meet only during my final year was supportive as well.

I just wanted to start a website to begin with, later I wanted it to be a networking platform, on further working I wanted it to be an educational platform, this was all on the paper.

Years later, practically I started with a blogging platform, later upgraded to an E-commerce platform which was further brought under incorporation.

Currently, I own 3 websites, 1 personal(mohanma.com), 2 brands(sumshowdone.com & bookcorridor.com) under 1 company(Sumshowdone Technologies Private Limited).

I had my first job offer through campus placement in my final year of Engineering(2011). The thought of starting a company was always there, I had come close in 2013 but could never materialize plan into action that year. I owned my first website in 2014(sumshowdone.com), became a online merchant in 2015, incorporated a company in 2016, owned my second website(bookcorridor.com) in 2017 and owned my third website in 2018(mohanma.com – this was spontaneous).

Startup landscape has seen a huge shift compared to 2010, the number of users in the industry that I operate has seen an upward lateral shift.

The kind of people that I have got to meet in this field is something different from a corporate life.

Entrepreneurship gives you freedom, with freedom comes great responsibility.

Value creation is the biggest form of reward that an entrepreneur yearns for, if tomorrow you want  to be an entrepreneur, you should be concentrating on a product or service that can change somebody’s life or make the buyer a happier person.

Things that I learnt being an entrepreneur:

  • If you want to do it you just do it(gut feeling).
  • Face your fears.
  • Never postpone, time is a very important resource.
  • Reading plays a very important role in shaping your thought process.
  • Failures are stepping stones to success.

The amount of knowledge and learning you acquire being an entrepreneur is tremendous.

An Entrepreneur should be ready to wear all hats from being a leader to a office boy.

Each one of us is knowingly or unknowingly an entrepreneur at some point. I believe at the end it’s all about your temperament, your adaptability combined with serenity.