Getting Started with Python – Python is an interpreted language

python programming languageWhen you compile a program written in C or Fortran generate an executable . To run this executable we need only very little , in the case of a ” hello, world ” enough to simply run it. The operating system considers executable and simply fulfills his orders .

This is not so in interpreted languages ​​. The Python code never gets translated into something that the operating system can understand. In Python the program terminates itself become an assembler that a virtual machine can understand and execute. The main consequence of this method is that it is imperative to have a Python interpreter installed on your computer in order to run Python code .

This is not today too severe condition. The only major OS that does not have a Python interpreter installed by default is Windows. Linux , Mac OSX , Solaris and AIX among others have one , but sometimes compensates install a more current than we find in the distribution of the operating system version . In the special case of Windows will simply download an installer, double clicking and say yes to everything .

When we execute Python code we launched an interpreter who is able to understand this language . Unlike static languages ​​like C or Fortran compiler which converts the code into an executable program that the operating system can understand.
Python is an interactive language

Python has an interactive console that will play a bit before writing the odd program.
_images / consola.png

Python console window in IDLE in Linux

The way to access this console differs depending on the operating system. On UNIX and derivatives simply open console and type in her system python . In Windows it is sufficient to open the corresponding program that is sure to Python shell or something is called .

Once we are in front of the Python interpreter we can start playing. In this respect it is a language similar to Matlab programming , so we can try to make a sum without problems.

2 +2 >>>
4

As you surely shall attempt to do something more complicated with numbers, much of the basic mathematical functions are in the math module, but we’ll get to that.
Python is a dynamic language

Python does not have to declare any variable. Each variable is the type you have in each case what is on the right side of the assignment operator = . This is true the first time a variable is used as when you assign a value to an existing variable.

This is straightforward in the case of Python is an interpreted language because : most assignments resolve the type at runtime , not at compile time just as happens in Matlab or Octave .

Returning to the interpreter :

A = 2.3 >>>
B = 3.2 >>>
>>> Print a * b
7.36
A = 2 >>>
>>> Print type ( a)
<type ‘int’>
>>> Print a * b
6.4
>>> A = ‘ hello’
>>> Print type ( a)
<type ‘str’>
>>> Print a * b
Traceback (most recent call last) :
File ” <stdin> ” , line 1, in <module>
TypeError : can not multiply sequence by non -int of type ‘float’

I do not need to devote a chapter to what the print statement .

Obviamete , when we try to multiply a string by a floating point number get an error clearly identified as a type error.

Although Python is full of surprises . If your intución he tells you that an operation may be possible the best is implemented. Qizas of the success of Python is that the people who have been creating over the past two decades is particularly people list. For example … What happens if we multiply a word for 2 ?

>>> A = ‘ hello’
2 * a >>> print
holahola

Well we have twice hello . So if we take the definition of multiplication as a sequence of sums …

>>> Print a + a
holahola

Python is full of details of these so sometimes it is good to let go by intuition.
Python is an object-oriented language

The computer careers cover the fundamental concepts of object orientation requires an entire subject . Paraidgmas all programming is the most successful on record. Even Fortran from Fortran 2003 standard , supports object-oriented programming. Matlab was also another language that has historically ignored object orientation but also stand in their way . The first implementation of object oriented Matlab was so poor that was forgotten . The second they got a reasonable result by almost copy the Python approach .

However based programming is a long subject and miserably forgotten within the curricula of engineering careers so we have no choice but to leave a huge dent in this course.

I will focus on discussing what most basic and fundamental of what an item attributes and methods . Thus we see a class as a way of grouping variables , attributes, and functions that operate on these variables , methods .

It is impossible to talk about and not talk about Python object orientation because practically everything in Python is an object. For example, a complex number is a particularly simple example.

>>> C = 2 +3 j
>>> Print c , type ( c )
(2 +3 j ) <type ‘complex’>
C.Real >>>
2.0
c.imag >>>
3.0
* >>> Print c (1j ) +3
2j

Python has a special constant , j is the imaginary unit . As in Matlab and Octave is advisable to use a number as a suffix such as in the example . Any imaginary number has two attributes , its real part and imaginary part .

While the sum of a complex number is a trivial operation ( the sum of its real and imaginary parts respectively) multiplication is not. This means that the complex operation class product is defined internally . We can see all the attributes , methods and operations available to a class using the help function.

>>> Help ( c )
Help on complex object :

complex class (object )
| Complex (real [ , imag ] ) -> complex number
|
| Create a complex number from real part and an imaginary part optional .
| This is equivalent to (real + imag * 1j ) where imag defaults to 0 .
|
| Methods defined here :
|
| __ Abs__ ( … )
| X.__abs__ ( ) <==> abs ( x )
|
| __ Add__ ( … )
| X.__add__ ( y) < == > x + y
|
| __ Coerce__ ( … )
| X.__coerce__ ( y) <==> coerce ( x , y)

( … )

This feature appears as abs__ __ () function is actually the absolute value , so that these two operations :

>>> Abs ( c )
3.605551275463989
C.__abs__ >>> ()
3.605551275463989

They are equivalent in all respects .
In Python everything is modularized

This itself is an essential difference between Matlab / Octave and Python. In these languages ​​any function of the library is available to the interpreter. This means that, as the number of functions increases, also the probability of conflicts grow .

In Python all libraries , including the standard library are modularized . For example , if we calculate the sine of pi before we have to import the module containing both the sine function as the value of pi

Import math >>>
Math.sin >>> ( math.pi )
1.2246063538223773e -16

Two things to note:

Each module is itself an object. In this case , after importing math , we have reached the constant pi as an attribute of the module and function without such a method.
Almost all modules or scripts in Python import a module . We can import modules virtually any point in the execution but by convention are generally imported at first.

Now you may think that the sine function or : math: pi, math having to drag the name can be tedious , especially if there is a special intention of grouping the features in this module. If we only imported without pi and we can do it as follows :

>>> From math import sin, pi
>>> Sin ( pi)
1.2246063538223773e -16

You can also think … What if I have to import math module functions twenty ? Do I have to write them all in the call to import ? Obviously not . We can use a wildcard to import the content of the module and make it available to the program:

From math import * >>>
>>> Sin ( pi)
1.2246063538223773e -16
>>> Cos ( pi)
-1.0
>>> Tan ( pi)
– 1.2246063538223773e -16

Although this way to import the contents of the modules is very practical because it prevents forgetfulness is not recommended for production.
Python comes with batteries but no charger

In the introduction , it is always a bad idea not to read the introduction , I mentioned that to program in Python is a great idea I used to use an integrated development interface (IDE ) like Eclipse , something more sophisticated than IDLE .

When we say that Python includes batteries mentioned the fact that the standard library is huge compared to other programming languages ​​, it includes only basic functionality . The Python standard library even comes with the ability to generate graphical interfaces in any windows operating system.

But Python is not Matlab or Visual Basic in the sense that one must decide how to schedule , manage and run your scripts or modules. Moreover, because Python has the great feature of the meaning of a program depends on how you have written is almost essential to use a specific tool.

For example execute a “Hello , world ! ” Portable , ie , we can follow exactly the same method on any operating system.

Once open IDLE, on the File menu select New Window , which opens an editor where we can write the program. So in this new window we wrote the following :

if __ name__ == ‘ __main__ ‘ :
print ‘ Hello World ! ‘

_images / editor.png

IDLE editor for Python on Linux

Just after writing the two end points of the first line we see that the editor automatically puts us four characters from the left margin. The reason may seem purely aesthetic but leed program again . There is a conditional, an if , and no statement ends the block. There is no end or brackets that encapsulate executable statements .

What determines the priority of the code block is precisely the separation from the left margin . Anything indented after the colon is part of the if block . The need to use a specific tool to increase the user lies in the indentation of the code is handled. In IDLE, for example, to change just press the tab key or backspace at the beginning of each line to change .

But if we compare with the IDLE IDE Matlab we still longing for a lot of pieces : integrated help, something that allows us to navigate between objects, a debugger a profiler … Part of the fun of any programming language , and it is also the case in C or Fortran, is to reach a development environment with which we feel comfortable . Comfort is a very personal feeling and I help you get very little.

Now, in the editor window , and then run run seleccionad module or You press F5. In the performer a Hello, World! Appears.

The initial part , the if __ name__ == ‘ __main__ ‘ : Python is a convention which is to say that what is from this line has to be run when the file is run py . . We use it sometimes and see its importance below.
Python is also a calculator

The interpreter has all the usual arithmetic operations: addition , subtraction, multiplication, division …

Just make a couple of clarifications to language behavior . Recourse to the power symbol is the double asterisk , **, and Fortran.

Features of Python Programming Language

Features of Python Programming LanguageSimple Python Programming Language

Python is a simple and minimalistic programming language. Reading a good Python program feels like reading English (but a very strict English !) . The pseudo – code nature of Python is one of its great strengths as it allows focus on solving the problem rather than the syntax , ie the language itself.
Easy to Learn

As you can see , Python is extremely easy to get started programming because it offers an extraordinarily simple syntax , which as we mentioned .
Free and Open Source

Python is an example of a FLOSS (Free / Libre and Open Source Software – Free / Libre and Open Source Software ) . In simple terms, you can freely distribute copies of this software , read its source code, make changes , use pieces of it in new free programs , and generally what you want . FLOSS is based on a concept of a community that shares knowledge. This is one of the reasons why Python is so good, has been created and improved by a community who just want to see a better Python.
High Level Language

When you write programs in Python you should never worry about low-level details , such as managing the memory used by your program.
portable

Due to its nature of being Open Source , Python has been ported ( ie changed to make it work ) to various platforms. All your programs will work on any of these platforms without requiring any changes. However, you must be careful enough to avoid system -dependent features (ie libraries or modules that work only in a particular system ) .

You may use Python on Linux , Windows , Macintosh , Solaris , OS / 2 , Amiga, AROS , AS/400 , BeOS , OS/390 , z / OS , Palm OS , QNX , VMS, Psion , Acorn RISC OS , VxWorks , PlayStation , Sharp Zaurus , Windows CE and PocketPC !
interpreted

    This requires some explanation.

A program written in a compiled language like C or C + + is a source language translated ( as mentioned ) one spoken by the computer ( binary code , ie zeros and ones ) using a compiler with several options. When you run the program , the linker / loader software only stores the binary code in the computer memory and starts execution from the first instruction in the program.

When using an interpreted language like Python, there are no separate compilation and execution steps . Just run the program from the source code. Internally , Python converts the source code into an intermediate form called bytecodes and then translates them into the native language of your computer and running . This makes using Python much easier. You just have to run your programs – do not worry about linking and loading libraries, etc. . This makes it portable, as they only have to copy the code of your Python program in any other system and also work .
Object Oriented

Python allows procedures oriented and object-oriented programming . In procedure-oriented languages ​​, the program is built around procedures or functions which are nothing but reusable pieces of programs . In object-oriented languages, the program is built around objects which combine data and functionality. Python provides a powerful and simple way to use object-oriented programming , especially when compared to languages ​​like C + + or Java.
expandable

If you need a piece of code to run very fast, you can do it by typing it in C and then combine it with your Python program .
embeddable

You can embed Python within your program in C / C + + to provide facilities ” scripting ” within it.
Stretch Book

The Python Standard Library is huge indeed . It can help you do various things involving regular expressions, document generation , unit testing , tests, processes , databases , web browsers , CGI , FTP , email, XML , XML -RPC , HTML , WAV files , cryptography GUI (graphical user interfaces / graphical user interface ) using Tk , and other system -dependent functions . Remember, this is always available wherever Python is installed and is part of the so-called philosophy of Python ” batteries included ” (” batteries included ” )

In addition to the standard library , other libraries as superior to the Python Imaging Library is an amazing library for image manipulation .

summary

Python is an exciting and powerful language . It has the required performance and functionality that allow you to write programs in a fun and easy combination .

Python Language Tutorial – Python Best Practices

Python Language Tutorial:

Understanding your python code Python code is structured into blocks of code.Each block of code is differentiated from the other by its level of indentation. Official python guide stated that the level of indentation should be maintained as 4 spaces. But many people and organizations (Google) uses 2 space indentation in their code. I follow 4 space indentation strictly in my code.

A common mistake beginners make is to mix tabs and spaces. It’s a very common mistake and you should avoid repeating it at all cost. One way to do it is to modify you editor settings to have four spaces for tab. you will find this setting in almost all the modern editors. Choosing an editor Here is a short list of best editors for python out there

1. Netbeans http://netbeans.org/downloads/

2. Pydev Python IDE for Eclipse http://pydev.org/

3. http://www.jetbrains.com/pycharm/ More generic options

4. Notepad++ http://notepad-plus-plus.org/

5. Sublime Text http://www.sublimetext.com/ I recommend, using sublimetext or notepad++ along with a python centric IDE like Pydev.

As a beginner you should make note of a few things and follow them consistently, I have compiled a short list here:

1. Indent your code properly and never mix tabs and spaces.

2. Leave one blank line between functions and two between classes(we will be covering functions and classes in the next few posts till them keep this in mind).

3. Debugging your code Read and understand the errors.

This is probably the most useful thing you will ever do to enhance your learning curve. Don’t ignore the errors, read it loud and understand what it is saying, and try to modify your code.If you can’t debug your code , google the error you get, you will find help that way.

4. Getting Help While implementing your ideas in coding, you will find a lot of hurdles and pitfalls, knowing where to look can be very effective in solving your doubts.

1. Do a Google search, starting with the word “python”, like “python list” or “python string lowercase”. The first hit is often the answer. This technique seems to work better for Python than it does for other languages for some reason.

2. The official Python docs site — docs.python.org — has high quality docs. Nonetheless, I often find a Google search of a couple of words to be quicker.

3. There is also an official Tutor mailing list specifically designed for those who are new to Python and/or programming!

4. Many questions (and answers) can be found on StackOverflow. For more detailed and realtime help you can visit the python chatroom http://chat.stackoverflow.com/rooms/6/python or join #python on irc freenode.

5. Using the interpreter Inside the Python interpreter, the help() function pulls up documentation strings for various modules, functions, and methods. These doc strings are similar to Java’s javadoc.

This is one way to get quick access to docs. Here are some ways to call help() from inside the interpreter:

help(len) — docs for the built-in len function (note here you type “len” not “len()” which would be a call to the function) help(sys)

— overview docs for the sys module (must do an “import sys” first) dir(sys)

— dir() is like help() but just gives a quick list of the defined symbols help(sys.exit)

— docs for the exit() function inside of sys help(‘xyz’.split)

— it turns out that the module “str” contains the built-in string code, but if you did not know that, you can call help() just using an example of the sort of call you mean: here ‘xyz’.foo meaning the foo() method that runs on strings help(list)

— docs for the built-in “list” module help(list.append) — docs for the append() function in the list module

Python Language Tutorial – Strings

Python has a built-in string class named “str” with many handy features (there is an older module named “string” which you should not use). String literals can be enclosed by either double or single quotes.

Python strings are “immutable” which means they cannot be changed after they are created (Java strings also use this immutable style). Since strings can’t be changed, we construct *new* strings as we go to represent computed values. So for example the expression (‘hello’ + ‘there’) takes in the 2 strings ‘hello’ and ‘there’ and builds a new string ‘hellothere’.

Python uses zero-based indexing, so if str is ‘hello’ str[1] is ‘e’. If the index is out of bounds for the string, Python raises an error.

s = 'hi'
  print s[1]          ## i
  print len(s)        ## 2
  print s + ' there'  ## hi there

Multi line strings

 multi = """It was the best of times.
  It was the worst of times."""

String Methods

Here are some of the most common string methods. A method is like a function, but it runs “on” an object. If the variable s is a string, then the code s.lower() runs the lower() method on that string object and returns the result (this idea of a method running on an object is one of the basic ideas that make up Object Oriented Programming, OOP). Here are some of the most common string methods:

s.lower(), s.upper() -- returns the lowercase or uppercase version of the string

s.strip() -- returns a string with whitespace removed from the start and end

s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character classes

s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string

s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index 
where it begins or -1 if not found

s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'

s.split('delim') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular 
expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case 

s.split() (with no arguments) splits on all whitespace chars.

s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

A google search for “python str” should lead you to the official python.org string methods which lists all the str methods.

Python does not have a separate character type. Instead an expression like s[8] returns a string-length-1 containing the character. With that string-length-1, the operators ==, <=, … all work as you would expect, so mostly you don’t need to know that Python does not have a separate scalar “char” type.

Next up, we discuss more string methods.

Python Language Tutorial – Hello world

Visit Python.org/download/

 

Python Language Tutorial:

Open the command line tool on your operating system and type the following,

>>> print 'hello world'
hello world

This is how you print a string in python. Play with it a little, try printing integers , floating point decimals , special characters, play and learn. Now let’s make this a little more complicated, what we will be making is a program that will take input from the user and print something like “hello world [input]” where [input] is the input the user enters. So let’s get started, folks The commands will be explained to you in a bit, first open up an editor and write the following in to it. (pro-tip: please don’t copy/paste it, write it instead, that’s the way you learn stuff ).

#!/usr/bin/python

# import modules used here -- sys is a very standard one
import sys

# Gather our code in a main() function
def main():
print 'Hello there', sys.argv[1]
# Command line args are in sys.argv[1], sys.argv[2] ...
# sys.argv[0] is the script name itself and can be ignored

# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()

Now save the file as helloworld.py (preferably on your desktop) Now open up command line and type

$ python helloworld.py 'Alice'
Hello there Alice

You should get the output ‘Hello there Alice’ .It works, great. Play with it a little bit, try giving it integer arguments (it wont throw an exception ), floating point arguments etc. Now lets see how it works. The first line is the shebang line

#!/usr/bin/python

Why do we need it ? In order to run any python script, we need to tell the shell three things: 1. That the file is a script 2. Which interpreter we want to execute the script 3. The path of said interpreter The shebang #! accomplishes (1.). The shebang begins with a # because the # character is a comment marker in many scripting languages. The contents of the shebang line are therefore automatically ignored by the interpreter. The env command accomplishes (2.) and (3.) Next we have imported sys module from the python library using

import sys

The sys module contains system-level information, which you can use in your program.Like in this case we are using importing sys module to take input from the command-line into our program. Next we defined a function main. Which we will call in the very last line of our program. Now you must be curious, as to what the heck does this block do ?

if __name__ == '__main__':
main()

There are two ways to run a python program, one is the direct way , and the other one is to import it into another program (which we are going to cover shortly). This block of code makes sure that main() function is executed only when our helloworld.py file is executed directly, and not indirectly when importing it into another file, we don’t want that. Next up, we talk about python best practices before moving further into python.

Python Language Tutorial

What is python ?

The official definition of python programming language as given by python.org is as follows.

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built-in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development.

Python Language Tutorial:

Setting up python

This article will make you familiar with python and show you how to set up python on your computer.

Most operating systems other than Windows already have Python installed by default. To check that Python is installed, open a command line (typically by running the “Terminal” program), and type python

If you have python installed you will get an output like this ( The following is the output on my computer, which has ubuntu installed )

Python 2.7.3 (default, Aug  1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

If you get a response like, python command not recognized. Then you will have to install python.

2. Installing python on your machine

Windows

1. Visit the official Python download page (http://python.org/download/ ) and grab the Windows installer. Choose the 32-bit version or a 64-bit version depending upon your requirement.

2. Run the installer and accept all the default settings, including the “C:\Python27″ directory it creates.

3. Next, set the system’s PATH variable to include directories that include Python components and packages we’ll add later. To do this:

Right-click Computer and select Properties.
In the dialog box, select Advanced System Settings.
In the next dialog, select Environment Variables.
In the User Variables section, edit the PATH statement to include this:

C:\Python27;C:\Python27\Lib\site-packages\;C:\Python27\Scripts\;

And you’re done.Python is now installed on your PC. Open up the python interpreter by opening the command line and typing python.
you should see an output like this.

Python 2.7.3  (default, Apr 10 2012, 14:24) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or license for more information.
>>>

That’s it, you are all set to dive into python now. In the following posts you will learn how to write your first python program.