




Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Os melhores documentos à venda: Trabalhos de alunos formados
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Comunidade
Peça ajuda à comunidade e tire suas dúvidas relacionadas ao estudo
Descubra as melhores universidades em seu país de acordo com os usuários da Docsity
Guias grátis
Baixe gratuitamente nossos guias de estudo, métodos para diminuir a ansiedade, dicas de TCC preparadas pelos professores da Docsity
Este tutorial em português, traduzido do inglês, ensina python em 10 minutos. Aprenda sobre sua tipagem dinâmica, indentação, tipos de dados, strings, listas, tuplas, dicionários, funções, herança múltipla, exceções e entrada/saída de arquivos.
O que você vai aprender
Tipologia: Notas de aula
1 / 8
Esta página não é visível na pré-visualização
Não perca as partes importantes!
help(5) Help on int object: (etc etc) dir(5) ['abs', 'add', ...] abs.doc 'abs(number) -> number Return the absolute value of the argument.
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.
myvar, mystring = mystring, myvar Tipos de dados
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
mylist = ["List item 1", 2, 3.14]
else:
continue else:
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: pass Funções
funcvar = lambda x: x + 1
print(funcvar(1)) 2
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
class MyClass(object): common = 10 def init(self): self.myvariable = 3 def myfunction(self, arg1, arg2): return self.myvariable
classinstance = MyClass() classinstance.myfunction(1, 2) 3
classinstance2 = MyClass() classinstance.common
10
classinstance2.common 10
MyClass.common = 30 classinstance.common 30 classinstance2.common 30
classinstance.common = 10 classinstance.common 10 classinstance2.common 30 MyClass.common = 50
classinstance.common 10 classinstance2.common 50
class OtherClass(MyClass):
def init(self, arg1): self.myvariable = 3 print(arg1)
classinstance = OtherClass("hello") hello classinstance.myfunction(1, 2) 3
myfile.write("This is a sample string") myfile.close() myfile = open(r"C:\text.txt")
print(myfile.read()) 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 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()
myfile = open(r"C:\binary.dat") loadedlist = pickle.load(myfile) myfile.close()
print(loadedlist) 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 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") loadedlist = pickle.load(myfile) myfile.close() >>> print(loadedlist) ['This', 'is', 4, 13327] Miscelâneas
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]
any([i % 3 for i in [3, 3, 4, 4, 3]]) True
sum(1 for i in [3, 3, 4, 4, 3] if i == 4) 2 del lst1[0] print(lst1) [2, 3] del lst
number = 5 def myfunc():
print(number)
def anotherfunc():
print(number) number = 3 def yetanotherfunc(): global number
number = 3 Epílogo