Python
Primeiros passos
Python no
universo das linguagens
https://www.tiobe.com/tiobe-index/
https://spectrum.ieee.org/top-programming-languages/
O ambiente de desenvolvimento
https://repl.it/languages/python3
https://www.tutorialspoint.com/execute_python_online.php
Baixe o Python
https://www.python.org/downloads/
apt-cache search python* apt-get install python*
Após a instalação do PyCharm
Oi mundo!
Verifiquem suas instalações.
O Shell do Python
Esse é o modo “interativo” do Python, onde instruções são informadas uma a uma e
imediatamente executas.
Google Colab
Versão no colab
import sys
print( sys.version_info )
Escrevendo e rodando em Python
transcreva:
s = “oi “
s2 = “ mundo!”
print( s + s2 )
Compilado x interpretado
https://www.sciencedirect.com/topics/computer-science/interpreted- language#:~:text=Python%20is%20an%20interpreted%20language,like%20code%20for%20these%20languages.
Considerações:
Antes de programar...
programação.
pode ser resolvido.
Variáveis
f(x) = (ax+c) / b
as variáveis são “identificadas” por um nome.
Para cada LP existem um conjunto de termos que não podem ser utilizados como identificados – palavras-reservadas.
As LP podem ser CASE-SENSITIVE ou não.
– Quando a LP exige a declaração da variável, geralmente, é chamada de fortemente tipada.
Ex: 12 não é o mesmo que “12”
Variáveis em Python
Identificadores em Python
definido pela linguagem
Palavras reservadas
and | assert | break | class | continue |
del | elif | else | except | exec |
for | from | global | if | import |
is | lambda | not | or | pass |
raise | return | try | while | with |
and | assert | break | class | continue |
Tipos de dados
O Python 3 possui 5 tipos de dados:
int | long | float | complex |
10 | 51924361L | 0.0 | 3.14j |
100 | -0x19323L | 15.20 | 45.j |
-786 | 0122L | -21.9 | 9.322e-36j |
080 | 0xDEFABCECBDAECBFBAEl | 32.3+e18 | .876j |
-0490 | 535633629843L | -90. | -.6545+0J |
-0x260 | -052318172735L | -32.54e100 | 3e+26J |
0x69 | -4721885298529L | 70.2-E12 | 4.53e-7j |
Strings
Exemplos: #!/usr/bin/python str = 'Hello World!'
print( str )
print( str[0] )
print( str[2:5] )
print( str[2:] )
print( str * 2 )
# imprime o conteúdo de str (Hello World!)
# imprime apenas o 1o caractere (H) # imprime da 3a a 5 letra (llo)
# imprime da 3a letra até o final
# repete o conteúdo de str duas vezes
print( str + “ test“ ) # imprime o resultado da concatenação de str com test
Estrutura de Dados
(dictionaries – map)
Conversão de tipos de dados
converte string para int converte string para long converte string para float
converte um obj para string
converte um int para um caractere converte um int para um caractere unicode converte um char para um int
Operadores
| | | + - / | * % |
| < | <= | => > | == != |
| | | and | or |
| | | << >> | & | ~ ^ |
A | B | and | Or |
True | True | True | True |
True | False | False | True |
False | True | False | True |
False | False | False | False |
Sintaxe geral
Controle do fluxo de execução
if expressão_lógica : comando1
else:
comando2
Repetição (loops)
conta = 1
while conta<10: print(conta) conta += 1
condicao = True while(condicao):
print("BLOCO while() e condicao==True")
condicao = False else:
print("BLOCO ELSE e condicao==False")
Laço for
comandos
for letter in 'Python‘ :
print( 'Current Letter :', letter )
fruits = ['banana', 'apple', 'mango'] for fruit in fruits :
print( 'Current fruit :', fruit )
print( “fim“ )
Laço for com índice
#!/usr/bin/python
fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)):
print ( 'Current fruit :', fruits[index] )
print( "Good bye!“ )
Cuidado com a indentação...
Linhas grandes...
>>>total = \
a + \ b
>>> total
3
Funções de Entrada/Saída (E/S)
from help:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:
end:
string inserted between values, default a space.
string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Funções de Entrada/Saída (E/S)
input(prompt=None, /)
From help:
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
Exemplos de E/S:
str = input()
num = eval( input() )
Parâmetros da linha de comando
No shell o usuário pode entrar com os parâmetros, exemplo:
No programa:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Para tratar o caso 2, existe a opção “getopt.getopt ”
#!/usr/bin/python
import sys, getopt
def main(argv): inputfile = '' outputfile = '' try:
opts, args = getopt.getopt(argv, \ "hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts: if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>' sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"): outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
if name == " main ":
main(sys.argv[1:])
Fim do arquivo test.py
Ao executar este programa:
$ python test.py –h
usage: test.py -i <inputfile> -o
<outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o
<outputfile>
$ test.py -i inputfile Input file is " inputfile Output file is "
Referências
https://www.tutorialspoint.com/python/python_basic_syntax.htm