Em Python, como em qualquer linguagem de programação, fazer operações matemáticas é algo trivial.
Abaixo irei listar os operadores básicos presentes na linguagem com exemplos:
In [1]: # Adição
In [2]: 33 + 41
Out[2]: 74
In [3]: # Subtração
In [4]: 7321 - 549
Out[4]: 6772
In [5]: # Multiplicação
In [6]: 838 * 47
Out[6]: 39386
In [7]: # Divisão
In [8]: 751 / 56
Out[8]: 13.410714285714286
In [9]: # Módulo (retorna o resto de uma divisão)
In [10]: 51 % 4
Out[10]: 3
In [11]: # Exponenciação
In [12]: 75 ** 3
Out[12]: 421875
In [13]: # Divisão inteira (retorna a parte inteira da divisão, o quociente)
In [14]: 9 // 2
Out[14]: 4
Essas são as formas mais básicas de operações matemáticas. Mas a linguagem possui módulos "built-in", que já vêm com a linguagem, que auxiliam mais ainda a realização de operações matemáticas. Posso citar inicialmente o módulo "math" e o módulo "statistics", caso tenha curiosidade, abra um terminal Python e digite:
import math
help(math)
O retorno do comando será um texto informando tudo sobre o módulo math e as funções embutidas nele. Dentre elas, posso citar funções como:
FUNCTIONS
cos(x, /)
Return the cosine of x (measured in radians).
acos(x, /)
Return the arc cosine (measured in radians) of x.
degrees(x, /)
Convert angle x from radians to degrees.
exp(x, /)
Return e raised to the power of x.
factorial(x, /)
Find x!.
Raise a ValueError if x is negative or non-integral.
hypot(x, y, /)
Return the Euclidean distance, sqrt(x*x + y*y).
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /)
Return the base 10 logarithm of x.
pow(x, y, /)
Return x**y (x to the power of y).
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.
sin(x, /)
Return the sine of x (measured in radians).
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
Mas existem outras além dessas. Pode-se ver claramente que o módulo pode facilitar bastante o tratamento matemático dos dados.
Outro módulo ou library importante deste tópico é a lib "statistics". Da mesma forma que foi feito para a lib "math", no console Python:
import statistics
help(statistics)
A ajuda da lib é bem explicativa, então vou só dar uma pincelada abaixo:
FUNCTIONS
(...)
mean(data)
Return the sample arithmetic mean of data.
>>> mean([1, 2, 3, 4, 4])
2.8
>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)
>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')
If ``data`` is empty, StatisticsError will be raised.
median(data)
Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0
mode(data)
Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
3
This also works with nominal (non-numeric) data:
>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
'red'
If there is not exactly one most common value, ``mode`` will raise
StatisticsError.
stdev(data, xbar=None)
Return the square root of the sample variance.
See ``variance`` for arguments and other details.
>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827
variance(data, xbar=None)
Return the sample variance of data.
data should be an iterable of Real-valued numbers, with at least two
values. The optional argument xbar, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.
Use this function when your data is a sample from a population. To
calculate the variance from the entire population, see ``pvariance``.
Examples:
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095
Como em qualquer calculadora científica, as funções citadas realizam as funções de uma calculadora estatística.
Mas não é o foco do momento abordar essas libs, abordei-as aqui mais com intuito de mostrar a existência delas. Mais pra frente, ao abordar programas matemáticos, podemos ver a utilização dessas bibliotecas na prática.
Além do intuito de mostrar as bibliotecas, outro ponto importante desta postagem é mostrar uma das forma de leitura da documentação da linguagem e dos módulos. A documentação é a referência mais rica que se pode ter, o problema muitas vezes é o fato de ela ser mal escrita ou mal estruturada. Mas pode haver momentos em que você tem uma dúvida e não acha a resposta de jeito nenhum mas uma lida na documentação pode te dar a luz necessária. Pode não ser a referência ideal pra quem tá começando, a leitura muitas vezes é sacal, mas é importante saber da existência dela e saber usá-la quando necessário.
Pretendia abordar tipos de dados nesta postagem mas ela já ficou grandinha, então na próxima irei abordar esse assunto.