4.3 Começando com a linguagem Python

Autora:Bem-estar, Criado: 2019-04-28 09:55:02, Atualizado:

Fluff preliminar

Então, você quer aprender a linguagem de programação Python, mas não pode encontrar um tutorial conciso e ainda com todas as funcionalidades. Este tutorial tentará ensiná-lo Python em 10 minutos. Provavelmente não é tanto um tutorial como é um cruzamento entre um tutorial e uma folha de truques, por isso ele só vai mostrar alguns conceitos básicos para você começar. Obviamente, se você realmente quer aprender uma linguagem, você precisa programar nela por um tempo. Assumo que você já está familiarizado com programação e, portanto, ignorará a maioria das coisas não específicas da linguagem. As palavras-chave importantes serão destacadas para que você possa facilmente identificá-las.

Todos os exemplos no livro estão em Python 3, e se alguém aconselha você a usar 2, eles não são seus amigos.

Propriedades

O Python é fortemente tipado (ou seja, os tipos são aplicados), dinâmico, tipado implicitamente (ou seja, você não precisa declarar variáveis), sensível a minúsculas e minúsculas (ou seja, var e VAR são duas variáveis diferentes) e orientado a objetos (ou seja, tudo é um objeto).

Conseguir ajuda

A ajuda no Python está sempre disponível no interpretador. Se você quiser saber como um objeto funciona, tudo o que você tem a fazer é chamar help() ! Também úteis são dir() , que mostra todos os métodos do objeto, e .Doutor!, que mostra a sua cadeia de documentação:

>>> help(5)
Help on int object:
(etc etc)

>>> dir(5)
['__abs__', '__add__', ...]

>>> abs.__doc__
'abs(number) -> number

Return the absolute value of the argument.

Sintática

O Python não tem caracteres obrigatórios de terminação de instruções e os blocos são especificados por indentação. Indent para iniciar um bloco, dedent para terminar um. As instruções que esperam um nível de indentação terminam em um ponto (:). Os comentários começam com o sinal de libra (#) e são de linha única, as cadeias de linhas são usadas para comentários de linhas múltiplas. Os valores são atribuídos (de fato, os objetos são ligados a nomes) com o sinal de igual (=), e o teste de igualdade é feito usando dois sinais de igual (==). Você pode incrementar / diminuir os valores usando os operadores += e -=, respectivamente, pela quantidade à direita. Isso funciona em muitos tipos de dados, incluindo cadeias. Você também pode usar várias variáveis em uma linha. Por exemplo:

>>> myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print(mystring)
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

Tipos de dados

As estruturas de dados disponíveis no Python são listas, tuplas e dicionários. Os conjuntos estão disponíveis na biblioteca de conjuntos (mas são incorporados no Python 2.5 e posterior). As listas são como matrizes unidimensionais (mas você também pode ter listas de outras listas), os dicionários são matrizes associativas (também conhecidas como tabelas de hash) e os tuplas são matrizes unidimensionais imutáveis (Python arrays pode ser de qualquer tipo, para que você possa misturar, por exemplo, números inteiros, strings, etc. em listas/dicionários/tuplas). O índice do primeiro item em todos os tipos de array é 0.

>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again" # We're changing the item.
>>> mylist[-1] = 3.21 # Here, we refer to the last item.
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15 # This is how you change dictionary values.
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print(myfunction(mylist))
3

Você pode acessar os intervalos de matriz usando um ponto e vírgula (:). Deixando o índice inicial vazio assume o primeiro item, deixando o índice final assume o último item. A indexação é inclusiva-exclusiva, portanto, especificando [2:10] retornará itens [2] (o terceiro item, por causa da indexação 0) para [9] (o décimo item), inclusive (8 itens).

>>> mylist = ["List item 1", 2, 3.14]
>>> print(mylist[:])
['List item 1', 2, 3.1400000000000001]
>>> print(mylist[0:2])
['List item 1', 2]
>>> print(mylist[-3:-1])
['List item 1', 2]
>>> print(mylist[1:])
[2, 3.14]
# Adding a third parameter, "step" will have Python step in
# N item increments, rather than 1.
# E.g., this will return the first item, then go to the third and
# return that (so, items 0 and 2 in 0-indexing).
>>> print(mylist[::2])
['List item 1', 3.14]

Cordas

Suas cordas podem usar compassos simples ou duplos, e você pode ter compassos de um tipo dentro de uma cadeia que usa o outro tipo (ou seja, Ele disse hello. é válido).Citações triplas duplas (ou únicas)(). As strings do Python são sempre Unicode, mas há outro tipo de string que são bytes puros. Estes são chamados bystrings e são representados com o prefixo b, por exemplo bHello \xce\xb1. Para preencher uma string com valores, você usa o operador % (modulo) e um tuple. Cada %s é substituído por um item do tuple, de esquerda para direita, e você também pode usar substituições do dicionário, assim:

>>> print("Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-"))
Name: Stavros
Number: 3
String: ---

strString = """This is
a multiline
string."""

# WARNING: Watch out for the trailing s in "%(key)s".
>>> print("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"})
This is a test.

>>> name = "Stavros"
>>> "Hello, {}!".format(name)
Hello, Stavros!
>>> print(f"Hello, {name}!")
Hello, Stavros!

Declarações de controlo de fluxo

As instruções de controle de fluxo são if, for, e while. Não há switch; em vez disso, use if. Use for para enumerar através dos membros de uma lista. Para obter uma sequência de números que você pode iterar, use range() . A sintaxe dessas instruções é assim:

rangelist = list(range(10))
>>> print(rangelist)
range(0, 10)
>>> print(list(rangelist))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print("The second item (lists are 0-based) is 2")
elif rangelist[1] == 3:
    print("The second item (lists are 0-based) is 3")
else:
    print("Dunno")

while rangelist[1] == 1:
    print("We are trapped in an infinite loop!")

Funções

As funções são declaradas com a palavra-chave def. Argumentos opcionais são definidos na declaração da função após os argumentos obrigatórios, sendo atribuído um valor padrão. Para argumentos nomeados, o nome do argumento é atribuído um valor. As funções podem retornar uma tupla (e usando desempacotamento de tupla, você pode efetivamente retornar vários valores). As funções lambda são funções ad hoc que são compostas por uma única instrução. Os parâmetros são passados por referência, mas tipos imutáveis (tuplos, int, strings, etc.) não podem ser alterados no chamador pelo chamador. Isso ocorre porque apenas o local de memória do item é passado, e ligar outro objeto a uma variável descarta o antigo, então tipos imutáveis são substituídos. Por exemplo:

# Same as def funcvar(x): return x + 1
funcvar = lambda x: x + 1
>>> print(funcvar(1))
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print(passing_example(my_list, my_int))
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10

Classes

O Python suporta uma forma limitada de herança múltipla em classes. Variaveis e métodos privados podem ser declarados (por convenção, isso não é aplicado pela linguagem) adicionando um sublinhado principal (por exemplo _spam).

class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation

>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all instances.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

# This class inherits from MyClass. The example
# class above inherits from "object", which makes
# it what's called a "new-style class".
# Multiple inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print(arg1)

>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10

Exceções

As exceções no Python são tratadas com blocos try-except [exceptionname]:

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print("Oops, invalid.")
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print("We're done with that.")

>>> some_function()
Oops, invalid.
We're done with that.

Importação

Bibliotecas externas são usadas com a palavra-chave import [libname]. Você também pode usar from [libname] import [funcname] para funções individuais. Aqui está um exemplo:

import random
from time import clock

randomint = random.randint(1, 100)
>>> print(randomint)
64

Arquivo I/O

O Python tem uma ampla gama de bibliotecas embutidas. Como exemplo, aqui está como serialização (conversão de estruturas de dados para strings usando a biblioteca pickle) com arquivo I/O é usado:

import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = open(r"C:\\binary.dat", "wb")
pickle.dump(mylist, myfile)
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = open(r"C:\\text.txt")
>>> print(myfile.read())
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = open(r"C:\\binary.dat", "rb")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print(loadedlist)
['This', 'is', 4, 13327]

Outros

  • As condições podem ser encadeadas: 1 < a < 3 verifica que a é menor que 3 e maior que 1.
  • Você pode usar del para excluir variáveis ou itens em matrizes.
  • As compreensões de lista fornecem uma maneira poderosa de criar e manipular listas. Eles consistem em uma expressão seguida de uma cláusula for seguida de zero ou mais cláusulas if ou for, assim:
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print([x * y for x in lst1 for y in lst2])
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print([x for x in lst1 if 4 > x > 1])
[2, 3]
# Check if a condition is true for any items.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.

# Check for how many items a condition is true.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print(lst1)
[2, 3]
>>> del lst1
  • As variáveis globais são declaradas fora das funções e podem ser lidas sem quaisquer declarações especiais, mas se você quiser escrever para elas, você deve declará-las no início da função com a palavra-chave global, caso contrário, o Python vinculará esse objeto a uma nova variável local (cuidado com isso, é uma pequena captura que pode te atrapalhar se você não souber).
number = 5

def myfunc():
    # This will print 5.
    print(number)

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print(number)
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

Epilogo

Este tutorial não pretende ser uma lista exaustiva de todos (ou mesmo um subconjunto) do Python. O Python tem uma vasta gama de bibliotecas e muito mais funcionalidades que você terá que descobrir através de outros meios, como o excelente livro Dive into Python. Espero ter feito sua transição para o Python mais fácil. Por favor, deixe comentários se você acredita que há algo que poderia ser melhorado ou adicionado ou se há algo mais que você gostaria de ver (classes, manipulação de erros, qualquer coisa).


Mais.