Em Python:
def soma(a, b):
return a + b
print("Resultado: %d" % soma(102, 459))
Resultado: 561
Baixar e Instalar o Anaconda (Distribuição Python)
Inicializar o Spyder (IDE Python)
Atalhos Importantes:
Você pode testar comandos na janela de Console, os resultados são apresentados instantaneamente
12 * 3 + 64 - 3 / 4
99.25
x = 2.5
y = x ** 2
print(y)
6.25
"Texto normal"
'Texto normal'
'Teste de "aspas"'
'Teste de "aspas"'
"texto grande assim \
com várias linhas"
'texto grande assim com várias linhas'
"texto grande assim " + \
"com várias linhas"
'texto grande assim com várias linhas'
Formatação pode ser feita de duas maneiras:
"%.1f ao quadrado é %.1f" % (x, y) #old style
'2.5 ao quadrado é 6.2'
"{:.1f} ao quadrado é {:.1f}".format(x, y) #new style
'2.5 ao quadrado é 6.2'
Mais informações na documentação oficial
Escrevendo arquivo texto:
texto_filename = "meu-texto.txt"
with open(texto_filename, "w") as texto_file:
texto_file.write("Com Python\n")
texto_file.write("sou mais feliz\n")
texto_file.write("-- fim --\n")
Lendo arquivo texto:
with open(texto_filename, "r") as texto_file:
texto = texto_file.readline()
texto
'Com Python\n'
texto_lido = ""
with open(texto_filename, "r") as texto_file:
for line in texto_file:
texto_lido += line
print(texto_lido)
Com Python sou mais feliz -- fim --
Forma insegura de abrir um arquivo
Mais informações na documentação
clubes = ["Botafogo", "Criciuma", "Náutico", "Vitória"]
clubes[0]
'Botafogo'
Atenção: Indexação de vetores no Python inicia em 0 (zero)
# Listas podem ter diferentes tipos (porém, não é boa prática)
["maça", 1, 15.3, 0xB]
['maça', 1, 15.3, 11]
clubes.append("Bragantino")
clubes
['Botafogo', 'Criciuma', 'Náutico', 'Vitória', 'Bragantino']
clubes.insert(0, "Bahia")
clubes
['Bahia', 'Botafogo', 'Criciuma', 'Náutico', 'Vitória', 'Bragantino']
clube = clubes.pop(0)
clube
'Bahia'
clubes[-1]
'Bragantino'
clubes[2:]
['Náutico', 'Vitória', 'Bragantino']
clubes[1:4]
['Criciuma', 'Náutico', 'Vitória']
# Dicts
fruit_calories = {}
fruit_calories["apple"] = 53
fruit_calories["banana"] = 95
fruit_calories["orange"] = 63
# Getting dict keys
print("Fruits: ", fruit_calories.keys())
Fruits: dict_keys(['banana', 'orange', 'apple'])
# Getting dict values
print("Calories: ", fruit_calories.values())
Calories: dict_values([95, 63, 53])
# Query
print("Orange calories:", fruit_calories["orange"])
Orange calories: 63
# Formated response
print("Orange has {0} calories".format(fruit_calories["orange"]))
Orange has 63 calories
if len(texto_lido) > 100:
print("Texto Grande")
else:
print("Texto Pequeno")
Texto Pequeno
if len(texto_lido) > 100:
print("Texto Grande")
elif len(texto_lido) > 20:
print("Texto Médio")
else:
print("Texto Pequeno")
Texto Médio
for clube in clubes:
print(clube)
Botafogo Criciuma Náutico Vitória Bragantino
for i in range(1, 4):
print(i)
1 2 3
for i, clube in enumerate(clubes):
print (i+1, clube)
1 Botafogo 2 Criciuma 3 Náutico 4 Vitória 5 Bragantino
for clube in sorted(clubes):
print(clube)
Botafogo Bragantino Criciuma Náutico Vitória
import math
# De 0 a 10, imprime somente números pares e interromple se x >= 8
for x in range(10):
if x % 2 != 0:
continue # pula para próxima iteração (x+1)
if x >= 8:
break # finaliza o loop
print("{:<8d}{:8.2f}{: 8.2f}{: 8.2f}".format(x, math.pow(2,x), math.sin(x), math.cos(x)))
0 1.00 0.00 1.00 2 4.00 0.91 -0.42 4 16.00 -0.76 -0.65 6 64.00 -0.28 0.96
x = 2
i = 0
while i < 10 and x < 1000:
i += 1
x = x * 2
i, x
(9, 1024)
def count_char(word, char):
count = 0
for w in word:
if w == char:
count += 1
return count
count_char("ESSS", "S")
3
def count_char(text, char, case_sens=False, stop_eol=False):
count = 0
if stop_eol:
text = text.split("\n")[0]
if not case_sens:
text = text.lower()
char = char.lower()
for w in text:
if w == char:
count += 1
return count
count_char("ESSS", "s")
3
count_char("ESSS", "s", True)
0
# Melhor
count_char("ESSS", "s", case_sens=True)
0
count_char(texto_lido, "m")
3
count_char(texto_lido, "m", stop_eol=True)
1
import math
math.sin(3.14 / 2)
0.9999996829318346
math.sin(math.pi / 2)
1.0
Mais informações na documentação
import os
home_dir = os.path.expanduser("~")
home_dir
'C:\\Users\\itghisi'
import os
os.getcwd()
'X:\\py4eng-course\\notebooks\\webinar-2015'
os.path.isdir(r"C:\\Windows")
True
Mais informações na documentação
import numpy
Criação de Arrays
numpy.array([1.2, 10, 33, 12.4, 5])
array([ 1.2, 10. , 33. , 12.4, 5. ])
numpy.arange(10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
import numpy as np
np.zeros(10, "d")
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
numpy.random.randint(1, 10, 10)
array([7, 6, 6, 3, 8, 1, 8, 3, 2, 8])
r = np.linspace(0, np.pi/2, 10)
Mais informacões no manual da NumPy
Operações Básicas
v = np.sin(r)
v > 0.5
array([False, False, False, False, True, True, True, True, True, True], dtype=bool)
v * 10
array([ 0. , 1.73648178, 3.42020143, 5. , 6.4278761 , 7.66044443, 8.66025404, 9.39692621, 9.84807753, 10. ])
v / 10
array([ 0. , 0.01736482, 0.03420201, 0.05 , 0.06427876, 0.07660444, 0.08660254, 0.09396926, 0.09848078, 0.1 ])
A = np.array([[3, 12, 4],
[0, 3, 9],
[1, 4, 3]])
x = np.array([3, 4, 4])
np.dot(A, x)
array([73, 48, 31])
Manipulação de Arrays (slicing)
v[-1]
1.0
v[0:5]
array([ 0. , 0.17364818, 0.34202014, 0.5 , 0.64278761])
v[-3:]
array([ 0.93969262, 0.98480775, 1. ])
np.concatenate([x, np.dot(A, x)])
array([ 3, 4, 4, 73, 48, 31])
Mais informacões no manual da NumPy
import matplotlib.pyplot as plt
plt.plot(v)
[<matplotlib.lines.Line2D at 0x7967320>]
%matplotlib inline
plt.plot(r, v)
[<matplotlib.lines.Line2D at 0x79dbe10>]
plt.plot(r, v, "ro")
plt.xlabel("x")
plt.ylabel("$sin(x)$")
plt.title("Tutorial do Plot")
<matplotlib.text.Text at 0x80c7f28>
Mais Informações:
import scipy.integrate
fx, err = scipy.integrate.quad(math.cos, 0, math.pi/2.0)
fx
0.9999999999999999
from scipy.integrate import quad
fx, err = quad(math.cos, 0, math.pi/2.0)
fx
0.9999999999999999