About

Swaroop C H is 26 years of age. He graduated in B.E. (Computer Science) from PESIT, Bangalore, India. He has previously worked at Yahoo! and Adobe.

More about

Page
Personal tools
Collection

Python pt-br:Fundamentos

From Notes

Jump to: navigation, search

Imprimir 'Olá mundo' não é suficiente, ou é? Você quer fazer mais que isso - você quer inserir dados, manipulá-los e obter alguma resposta a partir deles. Nós podemos conseguir isso em Python usando constantes e variáveis.

Contents

[edit] Constantes Literais

Um exemplo de uma constante literal é um número como 5, 1.23, 9.25e-3 ou uma string (sequência de caracteres) como 'Esta é uma string' ou "É uma string!". Ela é denominada literal porque é literal - você usa seu valor literalmente. O número 2 sempre representa a si mesmo e nada além disso - ele é uma constante pois seu valor não pode ser mudado. Logo, todos esses valores referem-se a constantes literais.

[edit] Números

Os números em Python são são de três tipos - inteiros, ponto flutuante e complexos.

  • 2 é um exemplo de inteiro, os inteiros são os números redondos.
  • 3.23 e 52.3E-4 são exemplos de números de ponto flutuante (ou floats, para abreviar). A notação E indica as potências de 10. Neste caso, 52.3E-4 significa 52.3 * 10-4.
  • (-5+4j) e (2.3 - 4.6j) são exemplos de números complexos.
Nota para programadores experientes
Não há o tipo 'long int' (inteiro longo) em separado. O tipo inteiro padrão pode assumir qualquer valor grande.

[edit] Strings

Uma string é uma sequência de caracteres. As strings são basicamente um amontoado de palavras. As palavras podem estar em inglês ou em qualquer língua que seja suportada pelo padrão Unicode, que atende a quase todas as línguas do mundo.

Nota para programadores experientes
Não há strings "somente em ASCII" porque o padrão Unicode engloba o ASCII.
Por convenção, todas as stringas estão em UTF-8.

Eu posso garantir que você usará strings em quase todos os programas que escrever em Python, portanto preste atenção à próxima parte sobre como usar strings em Python.

[edit] Aspas Unitárias

Você pode especificar as strings usando aspas unitárias (ou apóstrofes) tais como 'Use aspas unitárias em mim'. Todos os espaços em branco, isto é, espaços e tabulações são preservados no estado em que se encontram.

[edit] Aspas Duplas

As strings em aspas duplas trabalham exatamente da mesma maneira que as strings em aspas unitárias. Eis um exemplo: "Qual é o seu nome?"

[edit] Aspas Triplas

Você pode especificar strings que ocupam várias linhas usando aspas triplas - (""" ou '''). Você pode usar aspas unitárias e aspas duplas livremente para formar as aspas triplas. Eis um exemplo:

   '''Esta é uma string multi-linha. Esta é a primeira linha.
    Esta é a segunda linha.
    "Qual é o seu nome?", eu perguntei.
    Ele disse "Bond, James Bond."
    '''

[edit] Seqüências de Escape

Suponha que você queira obter uma string que contenha um apóstrofe ('), como você escreverá essa string? Por exemplo, a string é What's your name?. Você não pode escrever 'What's your name?' porque o Python ficará confuso sobre onde a string começa e onde termina. Logo, você terá que especificar que este apóstrofe não indica o fim da string. Isso pode ser feito com a ajuda do que é denominada uma sequência de escape. Você especifica o apóstrofe como \' - note a barra invertida. Agora, você pode escrever a string como 'What\'s your name?'.

Uma outra maneira de escrever essa string específica seria "What's your name?", isto é, usando aspas duplas. Da mesma maneira, você pode usar uma sequência de escape para inserir aspas duplas em uma string limitada por aspas duplas. Você também pode inserir a própria barra invertida usando a seqüência de escape \\.

O que fazer se você quer escrever uma string de duas linhas? Uma solução é usar uma string limitada por aspas triplas conforme foi ensinado previamente ou você pode utilizar uma seqüência de escape para o caracter de nova linha - \n para indicar o início da nova linha. Eis um exemplo, Essa é a primeira linha\nEssa é a segunda linha. Uma outra seqüência de escape útil a ser conhecida é a tabulação - \t. Há muitas outras seqüências de escape, mas eu mencionei aqui somente as mais úteis.

É importante observar que numa string, uma única barra invertida no fim da linha indica que a string continua na próxima linha, mas nenhuma linha nova é adicionada. Por exemplo:

   "Essa é a primeira frase.\
   Essa é a segunda frase."

equivale a "Essa é a primeira frase. Essa é a segunda frase.".

[edit] Strings Brutas

Se você precisa escrever algumas strings onde nenhum processamento especial tais como as seqüências de escape são manipuladas, então o que você precisa é escrever uma string bruta prefixando um r ou um R à string . Eis um exemplo, r"Novas linhas são indicadas por \n".

[edit] Strings São Imutáveis

Isso significa que uma vez que você tenha criado uma string, você não pode mudá-la. Embora isso pareça como algo ruim, não é realmente. Nós veremos porque isso não é uma limitação nos diversos programas que nós analisaremos mais adiante.

[edit] String Literal Concatenation

Se você colocar duas strings literais lado a lado, elas são automaticamente concatenadas pelo Python. Por exemplo, 'Qual é ' 'o seu nome?' é automaticamente convertido em "Qual é o seu nome?".

Nota para programadores C/C++
Não há tipo de dado char (caracter) separado em Python. There is no real need for it and I am sure you won't miss it.
Note for Perl/PHP Programmers
Remember that single-quoted strings and double-quoted strings are the same - they do not differ in any way.
Note for Regular Expression Users
Always use raw strings when dealing with regular expressions. Otherwise, a lot of backwhacking may be required. For example, backreferences can be referred to as '\\1' or r'\1'.

[edit] The format Method

Sometimes we may want to construct strings from other information. This is where the format() method is useful.

#!/usr/bin/python
# Filename: str_format.py
 
age = 25
name = 'Swaroop'
 
print('{0} is {1} years old'.format(name, age))
print('Why is {0} playing with that python?'.format(name))

Output:

   $ python str_format.py
   Swaroop is 25 years old
   Why is Swaroop playing with that python?

How It Works:

A string can use certain specifications and subsequently, the format method can be called to substitute those specifications with corresponding arguments to the format method.

Observe the first usage where we use {0} and this corresponds to the variable name which is the first argument to the format method. Similarly, the second specification is {1} corresponding to age which is the second argument to the format method.

What Python does here is that it substitutes each argument value into the place of the specification. There can be more detailed specifications such as:

>>> '{0:.3}'.format(1/3) # decimal (.) precision of 3 for float
'0.333'
>>> '{0:_^11}'.format('hello') # fill with underscores (_) with the text centered (^) to 11 width
'___hello___'
>>> '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python') # keyword-based
'Swaroop wrote A Byte of Python'

Details of this formatting specification is explained in the Python Enhancement Proposal No. 3101.

[edit] Variables

Using just literal constants can soon become boring - we need some way of storing any information and manipulate them as well. This is where variables come into the picture. Variables are exactly what they mean - their value can vary i.e. you can store anything using a variable. Variables are just parts of your computer's memory where you store some information. Unlike literal constants, you need some method of accessing these variables and hence you give them names.

[edit] Identifier Naming

Variables are examples of identifiers. Identifiers are names given to identify something. There are some rules you have to follow for naming identifiers:

  • The first character of the identifier must be a letter of the alphabet (uppercase ASCII or lowercase ASCII or Unicode character) or an underscore ('_').
  • The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores ('_') or digits (0-9).
  • Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter.
  • Examples of valid identifier names are i, __my_name, name_23, a1b2_c3 and resumé_count.
  • Examples of invalid identifier names are 2things, this is spaced out and my-name.

[edit] Data Types

Variables can hold values of different types called data types. The basic types are numbers and strings, which we have already discussed. In later chapters, we will see how to create our own types using classes.

[edit] Objects

Remember, Python refers to anything used in a program as an object. This is meant in the generic sense. Instead of saying 'the something', we say 'the object'.

Note for Object Oriented Programming users
Python is strongly object-oriented in the sense that everything is an object including numbers, strings and functions.

We will now see how to use variables along with literal constants. Save the following example and run the program.

How to write Python programs
Henceforth, the standard procedure to save and run a Python program is as follows:
  1. Open your favorite editor.
  2. Enter the program code given in the example.
  3. Save it as a file with the filename mentioned in the comment. I follow the convention of having all Python programs saved with the extension .py.
  4. Run the interpreter with the command python program.py or use IDLE to run the programs. You can also use the executable method as explained earlier.

[edit] Example: Using Variables And Literal Constants

# Filename : var.py
 
i = 5
print(i)
i = i + 1
print(i)
 
s = '''This is a multi-line string.
This is the second line.'''
print(s)

Output:

   $ python var.py
   5
   6
   This is a multi-line string.
   This is the second line.

How It Works:

Here's how this program works. First, we assign the literal constant value 5 to the variable i using the assignment operator (=). This line is called a statement because it states that something should be done and in this case, we connect the variable name i to the value 5. Next, we print the value of i using the print statement which, unsurprisingly, just prints the value of the variable to the screen.

The we add 1 to the value stored in i and store it back. We then print it and expectedly, we get the value 6.

Similarly, we assign the literal string to the variable s and then print it.

Note for static language programmers
Variables are used by just assigning them a value. No declaration or data type definition is needed/used.

[edit] Logical And Physical Lines

A physical line is what you see when you write the program. A logical line is what Python sees as a single statement. Python implicitly assumes that each physical line corresponds to a logical line.

An example of a logical line is a statement like print('Hello World') - if this was on a line by itself (as you see it in an editor), then this also corresponds to a physical line.

Implicitly, Python encourages the use of a single statement per line which makes code more readable.

If you want to specify more than one logical line on a single physical line, then you have to explicitly specify this using a semicolon (;) which indicates the end of a logical line/statement. For example,

   i = 5
   print(i)

is effectively same as

   i = 5;
   print(i);

and the same can be written as

   i = 5; print(i);

or even

   i = 5; print(i)

However, I strongly recommend that you stick to writing a single logical line in a single physical line only. Use more than one physical line for a single logical line only if the logical line is really long. The idea is to avoid the semicolon as far as possible since it leads to more readable code. In fact, I have never used or even seen a semicolon in a Python program.

An example of writing a logical line spanning many physical lines follows. This is referred to as explicit line joining.

   s = 'This is a string. \
   This continues the string.'
   print(s)

This gives the output:

   This is a string. This continues the string.

Similarly,

   print\
   (i)

is the same as

   print(i)

Sometimes, there is an implicit assumption where you don't need to use a backslash. This is the case where the logical line uses parentheses, square brackets or curly braces. This is is called implicit line joining. You can see this in action when we write programs using lists in later chapters.

[edit] Indentation

Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

This means that statements which go together must have the same indentation. Each such set of statements is called a block. We will see examples of how blocks are important in later chapters.

One thing you should remember is that wrong indentation can give rise to errors. For example:

i = 5
 print('Value is ', i) # Error! Notice a single space at the start of the line
print('I repeat, the value is ', i)

When you run this, you get the following error:

     File "whitespace.py", line 4
       print('Value is ', i) # Error! Notice a single space at the start of the line
       ^
   IndentationError: unexpected indent

Notice that there is a single space at the beginning of the second line. The error indicated by Python tells us that the syntax of the program is invalid i.e. the program was not properly written. What this means to you is that you cannot arbitrarily start new blocks of statements (except for the default main block which you have been using all along, of course). Cases where you can use new blocks will be detailed in later chapters such as the control flow chapter.

How to indent
Do not use a mixture of tabs and spaces for the indentation as it does not work across different platforms properly. I strongly recommend that you use a single tab or four spaces for each indentation level.
Choose any of these two indentation styles. More importantly, choose one and use it consistently i.e. use that indentation style only.
Note to static language programmers
Python will always use indentation for blocks and will never use braces. Run from __future__ import braces to learn more.

[edit] Summary

Now that we have gone through many nitty-gritty details, we can move on to more interesting stuff such as control flow statements. Be sure to become comfortable with what you have read in this chapter.



Please add your comments by clicking on the 'Discussion' link in the left sidebar.