Tuesday 28 February 2017

Top Interview Questions and Answers for Python


1) What is Python?
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable which uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.
2) Mention five benefits of using Python?
·          Python comprises of a huge standard library for most Internet platforms like Email, HTML, etc.
·          Python does not require explicit memory management as the interpreter itself allocates the memory to new variables and free them automatically
·          Provide easy readability due to use of square brackets
·          Easy-to-learn for beginners
·          Having the built-in data types saves programming time and effort from declaring variables

3) What is pickling and unpickling?
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function is called pickling.  While the process of retrieving original Python objects from the stored string representation is called unpickling.

Monday 27 February 2017

Applications of Python



3D CAD/CAM

FreeCAD is an Open Source CAx RAD based on Open Cascade, Qt and Python. It features some key concepts like Macro recording, Workbenches, ability to run as a server and dynamically loadable Application extensions and its designed to be platform independent.
Fandango is planned to be a full featured CAD program and has C++ core extensible by scripts. Currently the memory core for entity management is ready, scripting works wonderfully thanks to the ease of embedding and extending of Python. A KDE+XML user interface is now in place, controlling the keyboard and mouse.
Vintech RCAM is a CAD/CAM system for true shape nesting and NC programming of laser, plasma, oxy-fuel and water-jet cutting machines. Vintech RCAM is platform independent and now it runs under Windows XP, Windows 7 and Linux. The main programing language of the system is Python, which defines the advanced methodology and the dynamic system development.

Audio/Video Applications

cplay - Curses-based Linux multimedia jukebox
Freeseer - Conference recording software and screencast tool
Freevo - Linux multimedia jukebox
TimPlayer - Py-GTK based music player using GStreamer

Click Here To Obtain Source…

Thursday 23 February 2017

Exceptions in Python


What is an Exception?
An Exception is an event or error that would happen during the execution of a program that would disturbs their execution. Whenever there is an error, Python generates an exception that could be handled. It basically prevents the program from getting crashed. When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.
Why we use Exceptions
There was a valid as well as invalid exceptions occurred many times. Exceptions are convenient in many ways for handling errors and also the special conditions in a program. If we have some set of code which produces error, at that time we can use exception handling technique.

Handling an exception


If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include a except: statement, followed by a block of code that handles the problem as elegantly as possible.
If you have any queries? Mention it in the comment section, we will clarify you soon…!

Wednesday 22 February 2017

Introduction to Python for Big data Analytics


Hi everyone, if you are a fresher or experienced having lot of queries for learning which programming language. Don’t worry… we are providing a Webinar on Python for Big data Analytics. The title of the webinar is . We will be discussing the essential topics in detail and any queries can be rectified during the session.
Topics to be covered:
1. Introduction to Python
2. Python and Big Data
3. Python and Data Science
4. Key features of Python and their usage in Business Analytics
5. Business Analytics with Python – Real world Use Cases
Why Python?
Python is an interpreted, interactive, high level programming language similar to PERL with ease of accessibility, readability and having a simple syntax. Python is a preferred choice among professionals looking into Big Data Analytics and its feature of being a general-purpose, high level programming with a gradual learning curve makes it popular as compared to other programming languages.
Nowadays, most organizations would shift their emphasis to Big Data Analytics with an expected investment of over $50 billion. A simple and scalable tool is needed to analyze the big data, which has been answered by Python. In the today’s situation some of the most top organizations from search engine giants, like Google to NASA that are using Python for different purposes.
For more information also check out our on ‘Big Data Processing with Apache Storm’. Click Here to know more!   
If you have any queries?..Mention it in the comment section, we will clarify you!



Tuesday 21 February 2017

Brief Overview of Python

Introduction

Welcome! Are you completely new to programming? If not then we presume that you will be looking for information about why and how to get started with python. Fortunately you are a fresher or experienced programmer in any programming language would pick up Python very quickly. It’s easy for beginners use and learn, so jump in! Join Python Training in Chennai at Besant Technologies to Learn from here and finally remove ‘L’ from it!

Tuesday 14 February 2017

Why Learn Python?


Python is the great language for beginners which are easy to learn and maintain. To start programming in python, it’s easy to complete a program within two days. By using other languages it is extremely vast because in that go into its packages, like its machine learning packages, SciPy packages, Matplotlib and so on. So, it might take more time to complete.
  • Python’s biggest strength is that its bulk of library is portable.
  • There are millions of people around the world are working on Python and making contributions to its development.
  • It’s an open-source language. If you have Python in your system means write your own piece of package and then submit it for approval.
  • There are hundreds and thousands of packages available that are portable and helps in programming to clarify some of the stuff.
PyCharm
It is a GUI-based development environment having the Python packages connected to Python. For example, everyone has Twitter and Facebook accounts. How do analyze date from Twitter and Facebook? PyCharm package is used to
  • pull streaming data from Twitter or Facebook,
  • save it and conduct a search in it,
  • do a sentiment analysis, or
  • Run some kind of machine learning algorithm on it.
Many people worked hard in order to create these packages. Accordingly, all you have to do is read a little bit of documentation about this package and start implementing, instead of writing thousands of lines of code. Even in Python, you may end up it by writing 50-60 lines of code.
Machine Learning
Machine learning algorithms are mostly used to create artificial intelligence in machines which are also available in SciKit Learn. It has been optimized in a way that the machine learning code would write in just 4-5 lines. Use this package, invoke those procedures and functions, pass the data, fit your model and then predict the outcome which is very easy. Python has made lot of things easier and it is still being contributed by thousands of developers across the world. It’s going to get much better and that is why it’s becoming popular.
Data Analytics
With libraries like PyDoop and SciPy, it’s a dream come true for Big Data Analytics. Nowadays, there are tons of data flowing from everywhere, those would be analyzed first. In some organizations, they have the data from the past 70 years, while in others they have data from past 30-40 years and it’s too huge. They would store this data in some database somewhere, and it might be lost. Let’s take data of 1970s; but who cares about the 1970s data in this age? However, to find a trend, those data’s are important in a way. It’s not just important, it’s necessary to find a trend.
For example, I am in a computer manufacturing company and I want to find a trend as to what’s happening. You might have heard about forecasting and how people do that. Basically, they capture the data of the past 2-3 years. Let’s say, last year in March, the sales were 1 million, in April the number was 2 million, in May 3 million, and so on and so forth. They would just take this data and then extrapolate it to this year. Then, they assume that since last year in August, it was 1 million, this year too in August, it might be 1 million. That’s how they extrapolate it. So just look at the amount of data taken. May be in a couple of years when they average out the data of those years, they may do a moving average or use some kind of statistical algorithm but with a limited amount of data.
With the advent of Hadoop and Big Data, Data Processing has changed. Nowadays, we can process the data for 30 years and find a pattern, which might be anything. It should be sin wave or cosine wave to some graph, which is not any kind of wave, but just a zigzag graph which tell the pattern. In order to implement those algorithms with so much of data with the help of libraries like, PyDoop and SciPy.
Growing Interest in Python
Last 30 years the python has been there, but the growth of interest started in July, 2010. The name python is originated from the play in London (UK) doesn’t derive from the animal python (snake). In July 2010 the interest of Python started growing well to today itself. Most of the organizations, particularly the one dealing with data and Data Analytics asking the experienced and also having knowledgeable person in python.


If you have any queries? Mention it in the comment section, we will clarify you!

Friday 10 February 2017

Range Functions and Sequences in Python


Range() generates lists containing arithmetic progression.
Three variations of range() function
>> range(stop) – Starts from 0 till (stop – 1)
>> range(start,stop) – Ends at (stop – 1)
>> range(start,stop,step) – Step cannot be 0, default is 1
Example of Range Function
range(stop) - If the range is defined as 5, it would simply show the list of numbers falling in the range from 0 to 5. The default range starts from 0 and stops before 5, as defined.
range(start, stop) – The point of starting as well as stopping is defined in this. As shown in the example below, the start range has been defined as 5, while stop range as 10. Hence, it would display the numbers 5, 6, 7, 8, 9, which range between 5 to 10.
range(start, stop, step) - The first two values defined here are the same, start and stop, while the third one is step, which means the difference between every two consecutive numbers. For example, if range is defined in this way: range(0, 10, 2). It will give away numbers between 0 to 10, but with a difference of 2, in this way: [0, 2, 4, 6, 8]. The step here cannot be given 0 value. It has to be 1 or greater than 1.
Sequences in Python
A sequence is the succession of values bound together by a container that reflects their type. Almost every stream that we put in Python is a sequence.
Types of Sequences
  • Lists
  • Tuples
  • Xrange
  • String
The python is supported by some other sequences are strings, lists, tuples and Xrange objects. Python has a bevy of methods and formatting operations that can perform.
List
  • A list is a sort of container which holds the number of other objects, in a given order.
  • The list type implements the sequence protocol which allows adding and removing objects from the sequence.
  • It is an ordered set of elements enclosed in square brackets.
Simple definition of list – li = []
li = list() # empty list
li = list(sequence)
li = list(expression for variable in sequence)
example
            >>> list(a)
            [‘e’, ‘x’, ‘a’, ‘m’, ‘p’, ‘l’, ‘e’]
            >>> list3 = [‘Hadoop’, ‘Python’, ‘Data Science’, ‘Pig’, ‘hive’]
            >>> list3
            [‘Hadoop’, ‘Python’, ‘Data Science’, ‘Pig’, ‘hive’]
            >>> list3[2:]
            [‘Data Science’, ‘Pig’, ‘hive’]
            >>> list3[2:3]
            [‘Data Science’]
            >>> list3[2:4]
            [‘Data Science’, ‘Pig’]
            >>> list3[2:5]
            [‘Data Science’, ‘Pig’, ‘hive’]
            >>>
Accessing List Elements
To access the elements of a list:
n = len(li)
item = li[index] #Indexing
slice = li[start:stop] #Slicing
List Indexing

list[i] returns the value at index i, where i is an integer. A negative index accesses elements from the end of the list counting backwards. The last element of any non-empty list is always li[-1]. Python raises an IndexError exception, if the index is outside the list.

Accessing Command Line Arguments

Python supports the creation of programs that would run on the command line, completely with command-line arguments. It provides getopt modules that parse the command line options and arguments. The Python sys module provides access to any of the command-line arguments via sys.argv. It solves two purposes:
  • sys.argv is the list of command line arguments
  • len(sys.argv) is the number of command line arguments that are in the command line
  • sys.argv[0] is the program, i.e. script name

Executing Python

The python should be executed in the following
$python Commands.py inp1, inp2 inp3

Example

import sys
print ‘Number of arguments:’, len (sys.argv), ‘arguments.’
print ‘Argument List:’, str(sys.argv)
It will produce the following output:
Number of arguments: 4 arguments.
Argument List: [‘sample.py’, ‘inp1’, ‘inp2’, ‘inp3’]
If you have any queries? Mention them in the comments section and we will clarify you.

Wednesday 8 February 2017

Introduction to strings in python


In Python, the strings should be created by simply enclosing the characters in quotes. Python does not support the character types. These are treated as length-one strings, and are also considered as substrings. Substrings are immutable and can’t be changed once created.
Strings are the ordered blocks of text that are enclosed in single or double quotations. Thus, whatever is written in quotes, is considered as string. Though it can be written in single or double quotations, double quotation marks allow the user to extend strings over multiple lines without backslashes, which is usually the signal of continuation of an expression, e.g., ‘abc’, “ABC”.

Concatenation and Repetition

  • Strings are concatenated with the +sign:
>>> ‘abc’+‘def’
‘abcdef’
  • Strings are repeated with the *sign:
>>> ‘abc’*3
‘abcabcabc’

Indexing and Slicing Operation

  • Python starts the indexing at ‘0’
  • A string s will have indexes running from 0 to len(s)-1 (where len(s) is the length of s) in integer quantities.
  • S[i] fetches the ‘i’th element in the s.

Built-in String Methods

Following are the built-in String Methods that can be used in Python:
  • capitalize() – This method is used to capitalize the first letter of string.
  • count(str, beg= 0, end=len(string)) – Used to count how many times  the str occurs in string or in a substring of string, if beginning index ‘beg’ and ending index ‘end’ are given.
  • encode(encoding=‘UTF-8’,errors=‘strict’) – This method is used to return the encoded string version of string; on error, default raises a ValueError, unless the error is given with ‘ignore’ or ‘replace’.
  • decode (encoding=‘UTF-8’, errors=‘strict’) – This method is used to decode the string using the codec registered for Encoding. Encoding defaults to the default string function.
  • index(str, beg=0, end=len(string))- Same as find(), but it raises an exception if str is not found.
  • max(str)- Used to return the max alphabetical character from the string str.
  • min(str)- This is used to return the min alphabetical character from the string str.
  • replace(old, new [, max])- This method is used replace all the occurrences of ‘old’ in string with ‘new’ or maximum occurrences if max is given.
  • upper()- This method is used to convert the lowercase letters in a string to uppercase.

If you have any queries? Mention them in the comments section and we will clarify you.

Tuesday 7 February 2017

Python for DataScience


Python is the selection of information researchers. In nowadays python plays an important role to do their everyday exercises, as it has a differing scope of open-source libraries, and everything is free. The work of data scientists involves several interrelated activities, such as:
  • Accessing and manipulating data
  • Computing statistics
  • Creating visual reports on that data
  • Configuring predictive and explanatory models
  • Evaluating the models based on the additional data
  • Integrating the models into the production systems
If a data scientist wants to do some ad hoc analysis on data, he doesn’t write a Java code; the reason is java is too complicated for a data scientist to start programming. It has its own syntax and semantics, and every time there is a chance for developing a program in which one might run into a syntax or a semantic error, which nobody needs. Consequently, Pig and Hive were developed, however additionally we have Python in parallel, wherein you don't need to compose a great deal of lines of code.
The only thing that you need to remember in Python is indentation. Whenever a code is being written, in this time one needs to take care of spacing. If the indentation (spacing) is not proper, the program would be failed. If you are running a ‘for loop’, anything within the ‘for loop’ has to come a few inches inside the ‘for loop’. All lines of code should have same indentation or should be in one line.
SciPy
SciPy (pronounced as “sigh pie”) is Scientific Python which empowers the scientific analysis. It is a Python-based biological system of open-source software for mathematics, science, and engineering. We all have done differentiation, equation, etc. in mathematics, in school and college. Presently, how is it done in computers? It can be done in Octave as well, but Python provides us with SciPy which is the one that can perform such types of operations very easily. The Python that coordinates some libraries namely NumPy, SciPy library, Matplotib, IPython, Sympy, and pandas, and each one has its own role to play.

If you have any queries ? Specify them in the remarks area we will clarify you !..

Monday 6 February 2017

Introduction to python IDE

Introduction to python IDE

Python IDE (Integrated Development Environment) is a code editor, which allows editing of code making use of a series of peripheral components and attachments. The code editor we are using which almost gives the same result.

Features of Python IDE

  • It has  an ordinary text-editor
  • It offers a variety of language with specific shortcut editing functions.
  • Very fast and comfortable to use
  • Python is also an interpreter
PyCharm is one of the Python IDE code editors that are generally used by programmers.

Downloading PyCharm 

The Free Community Edition of PyCharm can be downloaded from the link below:
http://www.jetbrains.com/pycharm/download/

Starting Python

To start Python, you just need to type Python in your terminal command line and after that press enter.
The $ sign denotes the start of a terminal command line, and then the # sign denotes a comment. Python ignores anything written on the right side of # sign on a given line.

Using the Interpreter

  • In addition to being a programming language, Python is also an interpreter. It reads other Python programs and commands, and executes them.
  • Python programs are compiled automatically before being scanned by the interpreter. The hidden scanning process makes Python faster than a pure interpreter.
  • Once you’re inside Python, you can type commands at your own will.
  • Quantities stored in memory are not displayed by default
  • If the quantity is stored in memory, typing its name will display it.
  • To exit the interpreter, you need to press [Ctrl + D]

If you have any queries? Mention them in the comments section and we will clarify you.

Friday 3 February 2017

Python Database Access

Python Database Access

The Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard. Python Database API supports a wide range of database servers such as −
·        GadFly
·        MySQL
·        MySQL
·        PostgreSQL
·        Microsoft SQL Server 2000
·        Informix
·        Interbase
·        Oracle
·        Sybase
The DB API provides a minimal standard for working with databases using Python structures and syntax wherever possible. The MySQLdb module explains all concepts using MySQL. This API includes the following:
·        Importing the API module.
·        Acquiring a connection with the database.
·        Issuing SQL statements and stored procedures.
·        Closing the connection.
What is MySQL db?
MySQLdb is an interface for connecting to a MySQL database server from Python which implements the Python Database API v2.0 and it is built on the top of the MySQL C API.
How do I Install MySQLdb?
Before proceeding, make sure the MySQLdb is installed on the machine. Just type the following in Python script and execute it:
#!/usr/bin/python
Import MySQLdb
If it produces the below result, it means MySQLdb module is not installed:
           Traceback (most recent call last):
                       Import MySQLdb
           ImportError: No module named MySQLdb
Database Connection
Before connecting to the MySQL database, check the followings −
·        Create a database TESTDB.
·        Create a table EMPLOYEE in TESTDB.
·        This table has fields such as FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
·        User ID "testuser" and password "test123" are set to access TESTDB.
·        Python module MySQLdb is installed properly on the machine.
While running this script, the below result would be produced.
           Database version: 5.0.45
Creating Database Table
Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.
INSERT Operation
It is required when we want to create the records into a database table.
READ Operation
Fetch some useful information from the database. Once our database connection is established and then makes a query into this database.
·        fetchone() -  Fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.
·        fetchall() - Fetches all the rows in a result set. If some rows have already been extracted from the result set, then it retrieves the remaining rows from the result set.
·        Rowcount -  This is a read-only attribute, returns the number of rows that were affected by an execute() method.
Update Operation
Used to update one or more records that are already available in the database.
DELETE Operation
Used to delete some records from the database.
Performing Transactions
It is a mechanism that ensures data consistency having the following properties:
·        Atomicity - Either a transaction completes or nothing happens at all.
·        Consistency - A transaction must start in a consistent state and leave in a consistent state.
·        Isolation - Intermediate results of a transaction are not visible outside the current transaction.
·        Durability - Once a transaction was committed, the effects are persistent, even after a system failure.
The Python DB API 2.0 provides two methods to either commit or rollback a transaction.
COMMIT Operation
It gives a green signal to database to finalize the changes, and after this operation, no change can be reverted back.
ROLLBACK Operation
Revert back the changes completely by using use rollback() method.
Disconnecting Database
By using the close() method to disconnect the Database connection.
Handling Errors
There are many sources of errors. The DB API defines a number of errors that must exist in each database module. The exceptions are mentioned below.
·        Warning – Used for non-fatal issues.
·        Error – Base class for errors.
·        Interface Error – Used for errors in the database module not for the database itself.
·        Database Error – Used for errors in database.
·        Data Error – Subclass of database error which refers the errors in the data.
·        Operational Error – Refers the loss of connection to the database that are outside of control of the python scripter.
·        Integrity Error – Damage the relational integrity such as uniqueness constraints or foreign keys.
·        Internal Error – Refers to the errors internal to the database module.
·        Programming Error - Refers to the errors such as bad table name.
·        Not Supported Error – Refers that trying to call unsupported functionality.