Python 3.6.9 (default, Oct 29 2019, 10:39:36) [GCC] on linux Type "help", "copyright", "credits" or "license()" for more information. >>> numeros = [1, 2, "jessica"] >>> numeros [1, 2, 'jessica'] >>> >>> numeros.append(-7) >>> numeros [1, 2, 'jessica', -7] >>> numeros.insert(3, -10) >>> numeros [1, 2, 'jessica', -10, -7] >>> >>> #métodos de lista podem alterá-las (ou não) >>> help(numeros) >>> numeros.index(-7) #retorna o índice onde o objeto -7 aparece em numeros ou -1 se o objeto -7 não aparecer na lista numeros 4 >>> numeros [1, 2, 'jessica', -10, -7] >>> #resultado de métodos que alteram a lista não devem ser atribuídos à variáveis >>> #métodos de lista podem alterá-las (ou não) >>> >>> >>> #resultados de métodos que alteram listas não devem ser atribuídos à variáveis >>> #erro comum: vamos acrescentar o número -4 na lista >>> numeros = numeros.append(-4) #ERRADO. Não se deve atribuir o resultado do método append >>> numeros #o objeto apontados por numeros agora é none >>> >>> numeros = [1,2, 'jessica', -10, 7] >>> numeros.append(-4) #CERTO >>> numeros [1, 2, 'jessica', -10, 7, -4] >>> >>> numeros = [5, 0, 1, 3, -2, 4] >>> numeros.sort() #ordena a lista >>> numeros [-2, 0, 1, 3, 4, 5] >>> >>> #tuplas: arrays em Python (imutáveis). Tuplas são como listas imutáveis >>> valores = (8, 3, -1, 'jessica') >>> valores (8, 3, -1, 'jessica') >>> type(valores) >>> type(numeros) >>> >>> valores[-2] -1 >>> valores[0:3] (8, 3, -1) >>> >>> valores[0] = 200 #ERRO: TUPLA NÃO MUDA! Traceback (most recent call last): File "", line 1, in valores[0] = 200 #ERRO: TUPLA NÃO MUDA! TypeError: 'tuple' object does not support item assignment >>> >>> a = list(valores) >>> a [8, 3, -1, 'jessica'] >>> b = tuple(numeros) >>> b (-2, 0, 1, 3, 4, 5) >>> >>> 7/2 3.5 >>> 7//2 3 >>> >>> #conjuntos: coleção de ítens sem ordem e sem repetição >>> c = { 'jessica', 'carol', 'karen' } >>> c {'karen', 'jessica', 'carol'} >>> #c é do tipo conjunto (set) >>> c.add('leidiana') #adicionando um elemento ao conjunto >>> c {'leidiana', 'karen', 'jessica', 'carol'} >>> c.add('amanda') >>> c {'amanda', 'karen', 'jessica', 'carol', 'leidiana'} >>> #a "ordem" dentro do conjunto é aleatória (não existe ordem, na realidade) >>> 'carol' in c True >>> 'zumira' in c False >>> #conjunto em python só funciona com objetos imutáveis >>> c.add(7) >>> c {'amanda', 7, 'karen', 'jessica', 'carol', 'leidiana'} >>> c.add( [1,2,3] ) #erro! lista é objeto mutável Traceback (most recent call last): File "", line 1, in c.add( [1,2,3] ) #erro! lista é objeto mutável TypeError: unhashable type: 'list' >>> >>> c[2] #ERRO: não há indexação em conjuntos Traceback (most recent call last): File "", line 1, in c[2] TypeError: 'set' object does not support indexing >>> c {'amanda', 7, 'karen', 'jessica', 'carol', 'leidiana'} >>> >>> type(c) >>> >>> elemento = c.pop() #remove um elemento do conjunto e o retorna >>> c {7, 'karen', 'jessica', 'carol', 'leidiana'} >>> elemento 'amanda' >>> c.pop() 7 >>> c.pop() 'karen' >>> elemento 'amanda' >>> elemento = c.pop() >>> elemento 'jessica' >>> c {'carol', 'leidiana'} >>> c.add('mayara') >>> for nome in c: print(nome) mayara carol leidiana >>> len(c) 3 >>> #no conjunto, não existe a ideia de repetição >>> c {'mayara', 'carol', 'leidiana'} >>> c.add('carol') >>> c {'mayara', 'carol', 'leidiana'} >>> #acrescentar um ítem repetido ao conjunto não surte qualquer efeito >>> d = set() #gera um conjunto vazio >>> d set() >>> d.add(3) >>> d.add(9) >>> d.add(19) >>> d {19, 9, 3} >>> >>> #as operações de conjunto são definidas >>> c.union(d) {19, 'mayara', 3, 'carol', 9, 'leidiana'} >>> c {'mayara', 'carol', 'leidiana'} >>> d {19, 9, 3} >>> e = c.union(d) >>> e {19, 'mayara', 3, 'carol', 9, 'leidiana'} >>> c.intersection(e) #faz a interseção entre c e e {'leidiana', 'mayara', 'carol'} >>> >>> e {19, 'mayara', 3, 'carol', 9, 'leidiana'} >>> e.discard(9) >>> e {19, 'mayara', 3, 'carol', 'leidiana'} >>> >>> >>> numeros [8, -4, 10, 3, 7] >>> >>> nums = set(numeros) #podemos converter um conjunto em uma lista >>> nums {3, 7, 8, 10, -4} >>> >>> nums.intersection(e) {3} >>> float(e) #Erro: não faz sentido converter conjunto em lista Traceback (most recent call last): File "", line 1, in float(e) TypeError: float() argument must be a string or a number, not 'set' >>> >>> >>> #dicionários: são objetos que implementam mapeamentos (map) de objetos >>> d = {'cidade':'Belém', 'estado':'Pará', 'nome':'jéssica'} >>> #no dicionário, não há a ideia de ordem para os elementos >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'jéssica'} >>> len(d) 3 >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'jéssica'} >>> #todo ítem no dicionário precisa estar ligado a uma chave >>> #chaves: 'cidade', 'estado' e 'nome' (vem antes de : >>> #ítens: 'Belém', 'Pará' e 'jéssica' >>> #vamos acessar o ítem 'Pará' >>> d[1] #ERRO!, pois no dicionário não há ideia de ordem Traceback (most recent call last): File "", line 1, in d[1] #ERRO!, pois no dicionário não há ideia de ordem KeyError: 1 >>> d['estado'] 'Pará' >>> d['nome'] 'jéssica' >>> #dicionários são objetos mutáveis >>> d['nome'] = 'carol' >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'carol'} >>> type(d) >>> d2 = dict() #cria dicionário vazio >>> d2 {} >>> d3 = {} #dicionário vazio >>> d3 {} >>> type(d3) >>> >>> #podemos acrescentar ítens em um dicionário >>> d['pais'] = 'Brasil' >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'carol', 'pais': 'Brasil'} >>> #qualquer objeto pode ser ítem de um dicionário >>> #apenas objetos imjtáveis podem ser chaves em um dicionário >>> >>> mapa = { 1:7, 'casa':False, 3:[5,6,7], 9:{2,3,4} } >>> mapa {1: 7, 'casa': False, 3: [5, 6, 7], 9: {2, 3, 4}} >>> mapa[1] 7 >>> mapa[9] {2, 3, 4} >>> mapa['casa'] False >>> mapa[2] #ERRO! POIS NÃO EXISTE CHAVE 2 NO DICIONÁRIO Traceback (most recent call last): File "", line 1, in mapa[2] #ERRO! POIS NÃO EXISTE CHAVE 2 NO DICIONÁRIO KeyError: 2 >>> mapa[7] Traceback (most recent call last): File "", line 1, in mapa[7] KeyError: 7 >>> numeros [8, -4, 10, 3, 7] >>> numeros[0] 8 >>> numeros[3] 3 >>> >>> #podemos usar dicionario para simular uma lista >>> dicionumeros = {0:8, 1:-4, 2:10, 3:3, 4:7} >>> dicionumeros[0] 8 >>> dicionumeros[3] 3 >>> >>> valores = { 1:100, 2:500, 3:800, 4:1000 } >>> valores[0] Traceback (most recent call last): File "", line 1, in valores[0] KeyError: 0 >>> valores[1] 100 >>> valores[2] 500 >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'carol', 'pais': 'Brasil'} >>> d['cidade'] 'Belém' >>> #todo ítem precisa estar ligado a uma chave diferente em dicionários >>> len(d) 4 >>> >>> valores[0] + valores[1] Traceback (most recent call last): File "", line 1, in valores[0] + valores[1] KeyError: 0 >>> >>> valores[1] + valores[3] 900 >>> valores {1: 100, 2: 500, 3: 800, 4: 1000} >>> >>> valores[4] = 700 >>> valores {1: 100, 2: 500, 3: 800, 4: 700} >>> >>> >>> nums = {0:5, 1:30, 4:10, -1:100} >>> >>> nums[0] 5 >>> nums[1] 30 >>> nums[2] Traceback (most recent call last): File "", line 1, in nums[2] KeyError: 2 >>> nums[4] 10 >>> nums[-1] 100 >>> d {'cidade': 'Belém', 'estado': 'Pará', 'nome': 'carol', 'pais': 'Brasil'} >>> chaves = d.keys() #retorna uma listagem com as chaves de d >>> chaves dict_keys(['cidade', 'estado', 'nome', 'pais']) >>> listachaves = list(chaves) >>> listachaves ['cidade', 'estado', 'nome', 'pais'] >>> >>> values = d.values() >>> values dict_values(['Belém', 'Pará', 'carol', 'Brasil']) >>> >>> #percorrendo o dicionário >>> for chave in d.keys(): print( d[chave] ) Belém Pará carol Brasil >>> >>> >>> >>> >>> import math #importa a biblioteca math, no espaço de nomes math >>> >>> help(math) #exibe a ajuda do módulo math, listando todas as funções Help on module math: NAME math MODULE REFERENCE https://docs.python.org/3.6/library/math The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above. DESCRIPTION This module is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. acosh(...) acosh(x) Return the inverse hyperbolic cosine of x. asin(...) asin(x) Return the arc sine (measured in radians) of x. asinh(...) asinh(x) Return the inverse hyperbolic sine of x. atan(...) atan(x) Return the arc tangent (measured in radians) of x. atan2(...) atan2(y, x) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(...) atanh(x) Return the inverse hyperbolic tangent of x. ceil(...) ceil(x) Return the ceiling of x as an Integral. This is the smallest integer >= x. copysign(...) copysign(x, y) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. cos(...) cos(x) Return the cosine of x (measured in radians). cosh(...) cosh(x) Return the hyperbolic cosine of x. degrees(...) degrees(x) Convert angle x from radians to degrees. erf(...) erf(x) Error function at x. erfc(...) erfc(x) Complementary error function at x. exp(...) exp(x) Return e raised to the power of x. expm1(...) expm1(x) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(...) fabs(x) Return the absolute value of the float x. factorial(...) factorial(x) -> Integral Find x!. Raise a ValueError if x is negative or non-integral. floor(...) floor(x) Return the floor of x as an Integral. This is the largest integer <= x. fmod(...) fmod(x, y) Return fmod(x, y), according to platform C. x % y may differ. frexp(...) frexp(x) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(...) fsum(iterable) Return an accurate floating point sum of values in the iterable. Assumes IEEE-754 floating point arithmetic. gamma(...) gamma(x) Gamma function at x. gcd(...) gcd(x, y) -> int greatest common divisor of x and y hypot(...) hypot(x, y) Return the Euclidean distance, sqrt(x*x + y*y). isclose(...) isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(...) isfinite(x) -> bool Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(...) isinf(x) -> bool Return True if x is a positive or negative infinity, and False otherwise. isnan(...) isnan(x) -> bool Return True if x is a NaN (not a number), and False otherwise. ldexp(...) ldexp(x, i) Return x * (2**i). lgamma(...) lgamma(x) Natural logarithm of absolute value of Gamma function at x. log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(...) log10(x) Return the base 10 logarithm of x. log1p(...) log1p(x) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(...) log2(x) Return the base 2 logarithm of x. modf(...) modf(x) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. pow(...) pow(x, y) Return x**y (x to the power of y). radians(...) radians(x) Convert angle x from degrees to radians. sin(...) sin(x) Return the sine of x (measured in radians). sinh(...) sinh(x) Return the hyperbolic sine of x. sqrt(...) sqrt(x) Return the square root of x. tan(...) tan(x) Return the tangent of x (measured in radians). tanh(...) tanh(x) Return the hyperbolic tangent of x. trunc(...) trunc(x:Real) -> Integral Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 tau = 6.283185307179586 FILE /usr/lib64/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so >>> >>> >>> >>> >>> import math >>> math >>> >>> >>> math.exp(4) #retorna o exponencial de 4 54.598150033144236 >>> math.pi 3.141592653589793 >>> >>> math.cos( math.pi ) -1.0 >>> math.sin( math.pi ) 1.2246467991473532e-16 >>> >>> import math as ma #importamos o modulo math renomenando para ma >>> ma.pi #agora usamos ma.pi em vez de math.pi 3.141592653589793 >>> >>> >>> >>> import random #importa o módulo random >>> >>> random.random() #gera um número aleatório entre 0 e 1 0.48745234496388834 >>> >>> random.seed(1992) >>> random.random() 0.7140560271052792 >>> >>> >>> random.random() * 15 4.945579505173493 >>> >>> >>> random.randint(1, 52) #gera aleatório inteiro entre 1 e 52 30 >>> random.randint(0, 100) 54 >>> random.randint(0, 100) 95 >>> >>>