linguagem de programação de alto nível
Python é linguagem de programação de alto nível. sua finalidade geral e ilimitada, interativa e orientada a objeto. Python foi criada por Guido van Rossum no final dos anos oitenta e início dos anos noventa. Tal como Perl, Python código-fonte está disponível sob a GNU General Public License (GPL).
Python Resumo:
- Python é interpretada
- Python é Interactive
- Python é Object-Oriented
- Python é nova Linguagem
Python foi desenvolvida por Guido van Rossum no final dos anos oitenta e início dos anos noventa, no Instituto Nacional de Pesquisas para a Matemática e Ciência da Computação, na Holanda.
Destaques Python recurso incluem:
Fácil de aprender , Fácil de ler , Fácil de manter , Uma vasta biblioteca padrão , Modo interativo , Portable , Prorrogável , Bases de dados , Programação GUI , Scalonavél..
Como Python:
O mais up-to-date e código de fonte de corrente, binários, documentação, notícias, etc está disponível no site oficial do Python:
Python Official Website: http://www.python.org/
Você pode baixar a documentação do Python a partir do site abaixo. A documentação está disponível nos formatos HTML, PDF e PostScript.
Python Documentation Website: www.python.org/doc/
Primeira Python Programa:
Interactive Programming Mode:
Invocando o intérprete, sem passar um arquivo de script como parâmetro traz a seguinte pergunta:
root# python Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type “help”, “copyright”, “credits” or “license” for more info. |
>>>
Digite o texto que se segue para o direito do Python prompt e pressione a tecla Enter:
>>> print “Hello, Python!”; |
Isto produzirá seguinte resultado:
Hello, Python! |
Python Identificadores:
Um identificador de Python é uma denominação utilizada para identificar uma variável, função, classe, módulo ou outro objeto. Um identificador começa com uma letra de A a Z ou A a Z ou um sublinhado (_) seguido por zero ou mais letras, sublinhados e dígitos (0 a 9).
Python não permite caracteres de pontuação, como @, $ e% dentro de identificadores. Python é uma linguagem de programação caso sensível. Assim, e de recursos humanos Manpower são dois identificadores diferentes em Python.
Aqui estão identificador seguinte convenção de nomenclatura para Python:
- Nomes de classes começam com uma letra maiúscula e todos os outros elementos de identificação com uma letra minúscula.
- Iniciando um identificador com um sublinhado único líder, por convenção, indica que o identificador é para ser privado.
- Iniciando um identificador com dois underscores indica um identificador fortemente privado.
- Se o identificador também termina com dois sublinhados à direita, o identificador é uma linguagem definida pelo nome especial.
Palavras reservadas:
A lista a seguir mostra as palavras reservadas em Python. Estas palavras reservadas não podem ser utilizados como constante ou variável ou qualquer outro identificador nomes.
Palavras-chave conter apenas letras minúsculas.
and | exec | not |
assert | finaly | or |
breack | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
Linhas e Recuo:
Um dos programadores primeiro encontro ressalvas quando aprendendo Python é o fato de que não há chaves para indicar blocos de código para a classe e definições de função ou de controle de fluxo. Blocos de código são indicados por recuo de linha, que é rigidamente aplicadas.
O número de espaços no recuo é variável, mas todas as instruções dentro do bloco deve ser recuado no mesmo montante. Ambos os blocos neste exemplo são muito bem:
if True: print “True” else: print “False” |
No entanto, o segundo bloco, neste exemplo irá gerar um erro:
if True: print “Answer” print “True” else: print “Answer” print “False” |
Demonstrações Multi-Line:
Demonstrações em Python final tipicamente com uma nova linha. Python, no entanto, permitir a utilização do carácter de continuação de linha (\) para indicar que a linha deve continuar. Por exemplo:
total = item_one + \ item_two + \ item_three |
Declarações contidas nos [], (), ou () parênteses não precisa usar o caractere de continuação de linha. Por exemplo:
days = [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’] |
Cotação em Python:
Python aceita simples ( ‘), duplas ( “) e triplos (”’ ou” “) para denotar citações literais de cadeia, enquanto o mesmo tipo de citação começa e termina a string.
As citações triplo pode ser usado para abranger toda a cadeia em várias linhas. Por exemplo, todos os que se seguem são legais:
word = ‘word’ sentence = “This is a sentence.” paragraph = “””This is a paragraph. It is made up of multiple lines and sentences.””” |
Comentários em Python:
Um sinal de cardinal (#) que não está dentro de uma cadeia literal começa um comentário. Todos os caracteres após o # e até ao final de linha física são parte do comentário, o interpretador Python e ignora-los.
#!/usr/bin/python
# First comment |
Isto produzirá seguinte resultado:
Hello, Python! |
Um comentário pode ser na mesma linha depois de uma declaração ou expressão:
Você pode comentar várias linhas, como segue:
# This is a comment. # This is a comment, too. # This is a comment, too. # I said that already. |
Utilizar linhas em branco:
Uma linha contendo apenas espaços em branco, possivelmente com a comment, é conhecida como uma linha em branco, e Python ignora-lo.
Em uma sessão do interpretador interativo, você deve inserir uma linha vazia física para terminar uma declaração de várias linhas.
Várias declarações em uma única linha:
O ponto e vírgula (;) permite que várias instruções em uma única linha, uma vez que nem a declaração inicia um bloco novo código. Aqui está um recorte da amostra utilizando o ponto e vírgula:
import sys; x = ‘foo’; sys.stdout.write(x + ‘\n’) |
Vários grupos de comunicação como Suites:
Grupos de declarações individuais que compõem um único bloco de código são chamados de suites em Python.
Instruções compostas ou complexas, como se, ao mesmo tempo, def, e classe, são aqueles que necessitam de uma linha de cabeçalho e uma suite.
Linhas de cabeçalho iniciar a instrução (com a palavra-chave) e terminar com dois pontos (:) e são seguidos de uma ou várias linhas que compõem a suíte.
Exemplo:
if expression : suite elif expression : suite else : suite |
Python – Tipos de Variáveis:
As variáveis são nada além de localizações de memória reservado para armazenar valores. Isto significa que quando você cria uma variável você reservar algum espaço na memória.
Com base no tipo de dados de uma variável, o intérprete atribui memória e decide o que pode ser armazenada na memória reservada. Portanto, através da atribuição de diferentes tipos de dados variáveis, você pode armazenar números inteiros, decimais, ou personagens nessas variáveis.
Atribuindo valores a variáveis:
O operando à esquerda do operador = é o nome da variável e do operando à direita do operador = é o valor armazenado na variável. Por exemplo:
counter = 100 # An integer assignment miles = 1000.0 # A floating point name = “John” # A string |
print counter
print miles
print name
Standard Tipos de dados:
Python tem cinco tipos de dados padrão:
- Números
- String
- Lista
- Tupla
- Dicionário
Python Números:
Número de objetos são criados quando você atribuir um valor a eles. Por exemplo:
var1 = 1 var2 = 10 |
Python suporta quatro tipos diferentes de numérico:
- int (inteiros assinados)
- longa (inteiros longos [também pode ser representado em octal e hexadecimal])
- float (ponto flutuante valores reais)
- complexos (números complexos)
Aqui estão alguns exemplos de números:
int |
long |
float |
complex |
---|---|---|---|
10 | 51924361L | 0.0 | 3.14j |
100 | -0x19323L | 15.20 | 45.j |
-786 | 0122L | -21.9 | 9.322e-36j |
080 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-0490 | 535633629843L | -90. | -.6545+0J |
-0x260 | -052318172735L | -32.54e100 | 3e+26J |
0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Python Strings:
Strings em Python são identificados como um conjunto contíguo de caracteres entre aspas.
Exemplo:
str = ‘Hello World!’
print str # Prints complete string |
Python Listas:
Listas são o mais versátil dos tipos compostos Python’s de dados. A lista contém itens separados por vírgulas e incluídos entre colchetes ([]).
#!/usr/bin/python
list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ] print list # Prints complete list |
Python Tuplas:
Uma tupla é um outro tipo de dados de seqüência que é semelhante à lista. Uma tupla consiste de uma série de valores separados por vírgulas. Ao contrário de listas, porém, tuplas são colocados entre parênteses.
Tuplas pode ser pensado como de leitura apenas enumera.
tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 ) tinytuple = (123, ‘john’) |
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd to 4th
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists
Python Dicionário:
Python ‘s dicionários são do tipo tabela hash. Eles trabalham como arrays associativos ou hashes encontrado em Perl e consistem de pares chave-valor.
tinydict = {‘name’: ‘john’,’code’:6734, ‘dept’: ‘sales’} print dict[‘one’] # Prints value for ‘one’ key print dict[2] # Prints value for 2 key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # Prints all the values |
Python – Operadores Básicos:
Operator |
Description |
Example |
---|---|---|
+ | Addition – Adds values on either side of the operator | a + b will give 30 |
– | Subtraction – Subtracts right hand operand from left hand operand | a – b will give -10 |
* | Multiplication – Multiplies values on either side of the operator | a * b will give 200 |
/ | Division – Divides left hand operand by right hand operand | b / a will give 2 |
% | Modulus – Divides left hand operand by right hand operand and returns remainder |
b % a will give 0 |
** | Exponent – Performs exponential (power) calculation on operators | a**b will give 10 to the power 20 |
// | Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed. |
9//2 is equal to 4 and 9.0//2.0 is equal to 4.0 |
== | Checks if the value of two operands are equal or not, if yes then condition becomes true. |
(a == b) is not true. |
!= | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
(a != b) is true. |
<> | Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. |
(a <> b) is true. This is similar to != operator. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. |
(a > b) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. |
(a < b) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. |
(a >= b) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
(a <= b) is true. |
= | Simple assignment operator, Assigns values from right side operands to left side operand |
c = a + b will assigne value of a + b into c |
+= | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand |
c += a is equivalent to c = c + a |
-= | Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand |
c -= a is equivalent to c = c – a |
*= | Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand |
c *= a is equivalent to c = c * a |
/= | Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand |
c /= a is equivalent to c = c / a |
%= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand |
c %= a is equivalent to c = c % a |
**= | Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand |
c **= a is equivalent to c = c ** a |
//= | Floor Dividion and assigns a value, Performs floor division on operators and assign value to the left operand |
c //= a is equivalent to c = c // a |
& | Binary AND Operator copies a bit to the result if it exists in both operands. |
(a & b) will give 12 which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in eather operand. | (a | b) will give 61 which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (a ^ b) will give 49 which is 0011 0001 |
~ | Binary Ones Complement Operator is unary and has the efect of ‘flipping’ bits. |
(~a ) will give -60 which is 1100 0011 |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
a << 2 will give 240 which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
a >> 2 will give 15 which is 0000 1111 |
and | Called Logical AND operator. If both the operands are true then then condition becomes true. |
(a and b) is true. |
or | Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. |
(a or b) is true. |
not | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. |
not(a && b) is false. |
in | Evaluates to true if it finds a variable in the specified sequence and false otherwise. |
x in y, here in results in a 1 if x is a member of sequence y. |
not in | Evaluates to true if it finds a variable in the specified sequence and false otherwise. |
x not in y, here not in results in a 1 if x is a member of sequence y. |
is | Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. |
x is y, here is results in 1 if id(x) equals id(y). |
is not | Evaluates to false if the variables on either side of the operator point to the same object and true otherwise. |
x is not y, here is not results in 1 if id(x) is not equal to id(y). |
Python Operadores de Precedência
A tabela a seguir lista todos os operadores de maior precedência para a menor.
Operator |
Descrição |
---|---|
** | Exponentiation (raise to the power) |
~ + – | Ccomplement, unary plus and minus (method names for the last two are +@ and -@) |
* / % // | Multiply, divide, modulo and floor division |
+ – | Addition and subtraction |
>> << | Right and left bitwise shift |
& | Bitwise ‘AND’ |
^ | | Bitwise exclusive `OR’ and regular `OR’ |
<= < > >= | Comparison operators |
<> == != | Equality operators |
= %= /= //= -= += |= &= >>= <<= *= **= | Assignment operators |
is is not | Identity operators |
in not in | Membership operators |
note or and | Logical operators |
A instrução if:
A sintaxe da instrução if é:
if expression: statement(s) |
A declaração else:
A sintaxe da instrução if … else é a seguinte:
if expression: statement(s) else: statement(s) |
A Declaração elif
O sintaxe da instrução elif se … é:
if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s) |
Isto produzirá seguinte resultado:
3 – Got a true expression value 100 Good bye! |
A Nested se … Construir elif … else
A sintaxe do IF aninhado … elif … else const podem ser:
if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s) |
Ufa !