quarta-feira, 17 de fevereiro de 2010

Installing and playing a bit with Python 2.x

Recommendation: This article is aimed at users of Linux (I use Ubuntu 9.10). However, those who use MS Windows and Mac can take advantage of many of the things that are said here.

In this article we will see:
  • How to install Python 2.4 through the Shell Linux; 
  • Using Python on the command line itself Shell; 
  • How to run a python code (.py file) using the Shell; 
  • Where to learn Python. 

Installing Python 2.x through the Linux Shell:

Come on! Before you start coding you need to have Python installed on your computer. Many versions of Linux already have Python installed. Check this by typing in the Shell:

$ python

After that, press ENTER to confirm. By doing this you can see if Python is or is not installed on your machine (because his version will appear if you are) and at the same time, start your own.

Now, if you do not really have Python installed on your machine install it through the package manager APT-GET:

$ sudo apt-get install python2.4

Done the above steps you have prepared the Python environment and are ready to encode. The folder structure of Python when installed can be attested by typing one of the following commands:

$ whereis python

Or:

import sys
sys.path

In my case, the following result was shown - a list of paths:

['', '/usr/local/lib/python2.6/dist-packages/virtualenv-1.4.3-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages']


Using Python on the command line itself Shell:

To start, you type python Python Shell in Linux. Once that's done we can use the Python commands via the command line.
For example, if I want to know the result of the mathematical expression: 10 * 30 / 2, simply enter to get the number 150, which is the correct result:

10*30/2
150

Python can be used as a calculator: use the operators + (to add), - (to subtract), * (to multiplication) and / (to division). Do as the above operation. Enter values and operators to determine the outcome.

Let us for a more complete example. Enter the following commands:

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB
print "O resultado da soma é: " + str(result)

Well, what we did was something very simple: First (line 01) create a variable called varA and attach to it the value of the keyboard (raw_input). Then we transform the value entered into a floating point number (float()).
The same was done in the second line varB.
On line 03 we create another variable (called results) and attach to it the result of the sum of varA and varB.
Finally, in line 04 printed on standard output, the screen (print) the result for the variable results in transforming the character set (string) with str().
Along the same line the sign serves as a concatenation (and the comma (,), if you prefer), adding our message with our result, being a set of characters. If we had not used the function str() to transform results in string would cause an error, because objects of type float can not be concatenated with objects of type string.


Running a python code (.py file) using the Shell:

Files of type .py are understood by the interpreter python you have installed and can be run in the Shell. To create a file of this type simply open a text editor (VIM for example) and start code (hehehehe!).

$ vim calculo_sum.py

Then enter these codes, same as above, but with the increase in the first and second line on the encoding of the editor. Your code will get this:

#!/usr/bin/python
# vim: set fileencoding=utf-8:

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB
print "O resultado da soma é: " + str(result)

To run this program at Shell type:

$ python calculo_sum.py

And the program will run.

We will now increase our small program with some statements: the if/else commands, for example.
To not have problems with errors in the indentation, remember: always use the tabsize your editor with the value 4. Python does not have braces "{" "}" as a delimiter scope, so a bad indentation certainly give rise to errors.

In VIM, to configure the tabsize type:

:set ts=4

And the code will get this:

#!/usr/bin/python 
# vim: set fileencoding=utf-8:  

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB

if result < 0:
    print "Resultado final inferior a zero: " + str(result)
elif result > 0:
    print "Resultado final superior a zero: " + str(result)
else:
    print "Valor final igual a zero!"

Well, as was said this was just a simple example which defines the field response in three possibilities: negative, zero and positive.
We use the command "if, elif and else" to obtain it.


Where to learn Python:

On the internet there several websites that provide opportunities to study this programming language (and other).
I also noticed that the vast majority are in english. But for those who do not speak the language can also study in Brazilian websites.
Below is a short list of options. If you want to search for more references on Google or another search engine of your preference:

Instalando e brincando um pouco com Python 2.x

Recomendação: Este artigo é dirigido para os usuários de Linux (eu uso Ubuntu 9.10). Não obstante, quem usa MS Windows e MAC poderá aproveitar muitas das coisas que serão ditas aqui.

Neste artigo veremos:
  • Como instalar Python 2.4 via Shell do Linux;
  • Utilizando Python em linha de comando no próprio Shell;
  • Como rodar um código python (.py) utilizando o Shell;
  • Onde estudar Python.


Instalando Python 2.x via Shell do Linux:

Vamos lá! Antes de começar a codificar é necessário ter o Python instalado em seu computador. Muitas das versões do Linux já possuem o python instalado. Verifique isso digitando no Shell:

$ python


Após isso, tecle ENTER para confirmar. Ao fazer isso você poderá constatar se o Python está ou não instalado em sua máquina (pois a versão dele irá aparecer caso esteja) e, ao mesmo tempo, iniciará o próprio.

Agora, caso você não tenha realmente o Python instalado em sua máquina instale ele por meio do gerenciador de pacotes APT-GET:

$ sudo apt-get install python2.4

Feito os passos acima você preparou o ambiente Python e já está pronto para codificar. A estrutura de pastas do Python quando instalado pode ser atestada digitando-se um dos comandos abaixo:

$ whereis python


Ou ainda:

import sys
sys.path


No meu caso, o seguinte resultado foi exibido - uma lista com os caminhos:

['', '/usr/local/lib/python2.6/dist-packages/virtualenv-1.4.3-py2.6.egg', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/local/lib/python2.6/dist-packages']



Utilizando Python em linha de comando no próprio Shell:


Para iniciar o Python você digitará python no Shell do Linux. Feito isso já podemos utilizar os comandos do Python via linha de comando.
Por exemplo: se quero saber o resultado da expressão matemática: 10*30/2 basta apenas digitarmos para obtermos o número 150, que é o resultado correto:

10*30/2
150


O Python pode ser usado como calculadora: utilize os operadores + (para somar), - (para subtrair), * (para multiplicação) e / (para divisão). Faça como na operação acima. Digite os valores e os operadores para ter o resultado.

Vamos então para um exemplo mais completo. Digite os comandos abaixo:

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB
print "O resultado da soma é: " + str(result)


Bom, o que fizemos foi algo bem simples: Primeiro (linha 01) criamos uma variável chamada varA e atribuímos à ela o valor da entrada do teclado (raw_input). Em seguida transformamos o valor inserido em um número de ponto flutuante (float()).
O mesmo foi feito na segunda linha para varB.
Na linha 03 criamos outra variável (chamada results) e atribuímos à ela o resultado da soma entre varA e varB.
Por fim, na linha 04 imprimimos na saída padrão, a tela (com o print) o resultado atribuído à variável results transformando-a em conjunto de caracteres (string) com a função str().
Nesta mesma linha o sinal + funciona como um concatenador (assim como a vírgula (,), se preferir), juntando nossa mensagem com nosso resultado, sendo ele um conjunto de caracteres. Caso não tivessemos utilizado a função str() para transformar results em string ocasionaria um erro, pois objetos do tipo float não podem ser concatenados com objetos do tipo string.



Rodando um código python (.py) utilizando o Shell:

Arquivos do tipo .py são entendidos pelo interpretador python que você instalou e podem ser executados no ambiente Shell. Para criar um arquivo deste tipo simplesmente abra um editor de textos (VIM por exemplo) e comece a codificar (hehehehe!):

$ vim calculo_sum.py


E digite estes códigos, igual ao anterior, porém com o acréscimo na primeira e segunda linha relativo a codificação do editor. Seu código ficará com este aspecto:

#!/usr/bin/python
# vim: set fileencoding=utf-8:

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB
print "O resultado da soma é: " + str(result)


Para executar este programa digite no Shell:

$ python calculo_sum.py


E o programa será executado.

Vamos agora incrementar nosso pequeno programa com algumas instruções: o comando if/else por exemplo.
Para não ter problemas com erros de indentação, lembre-se: sempre utilize o "tabsize" do seu editor com o valor 4. O Python não possui chaves "{" "}" como delimitador de escopo, portanto uma má indentação com certeza ocasionará erros.

No VIM, para configurar o tabsize (tamanho da tabulação) digite:

:set ts=4


E o código ficará com este aspecto:

#!/usr/bin/python 
# vim: set fileencoding=utf-8:  

varA = float(raw_input("Digite um número: "))
varB = float(raw_input("Digite outro número: "))
result = varA + varB

if result < 0:
    print "Resultado final inferior a zero: " + str(result)
elif result > 0:
    print "Resultado final superior a zero: " + str(result)
else:
    print "Valor final igual a zero!"

Bem, como foi dito este foi apenas um simples exemplo ao qual delimita o campo de resposta em três possibilidades: Negativa, zero e positiva.
Utilizamos o comando "if, elif e else" para obtermos isso.


Onde estudar Python:

Na internet existe uma infinidade de websites que fornecem possibilidades para estudar esta linguagem de programação (e qualquer outra).
Notei também que a grande maioria está no idioma inglês. Mas para quem não domina o idioma é possível também estudar em websites brasileiros.
Abaixo segue uma pequena lista de opções. Caso queira mais referências procure no Google ou outro buscador de sua preferência: