Introdução ao Python

Em contexto prático de atividade

Sumário

 

  1. Python: contexto histórico e motivações
  2. Funcionamento do Python com exemplos
  3. Exemplos

2. Motivação

Porquê aprender Python?

  • Facilidade de leitura / escrita
  • Foco na estrutura do código
  • Gestão de memória automatizada
  • Bibliotecas Standard e extensões

One of Guido's key insights is that code is read much more often than it is written"

3. O que é o Python?

Uma breve explicação da linguagem

x = 3

4. Introdução prática

Aplicação

Python 101

Linha de comandos

Texto, contas

Impressões

Já o instalaram?

$   python
>>> print "done"

ou então...

http://pypyjs.org/

Os meus primeiros comandos

3 + 10
x = 10
x + 3
print x

 

  • A minha primeira conta
  • A minha primeira variável
  • O meu primeiro "print"

Variáveis

e tipos de variáveis

x = 10      # this is a comment, btw...
type(x)     # integer
y = "Rambo"
type(y)     # string, right?
x = 2.0
type(x)     # not an integer, anymore!
y = True
type(y)     # not a string, anymore!

 

Em Python, tipos são definidos, mas são inferidos pelo sistema e podem mudar

  • Integer (number)
  • String (text)
  • Boolean

Print...

name = "Bruce"
lastName = "Wayne"
nickname = "Batman"
age = 26

fullName = name + lastName                             
fullName = name + " " + lastName + ", the " + nickname

print fullName
print "I am " + fullName
print "I am %s" % (fullName)

print "I am %s \n and I am %d years old" % (fullName, age) 

 

Provide information to your users by printing...

Input

Exercises

Part 1

Your Pythonic name

Cria variáveis com:

  • O primeiro nome
  • O último nome
  • A tua idade
  • Algo sobre ti

Imprime esta informação recorrendo às variáveis e apenas a um print

I am James Bond, 26 years old, and I am the coolest!

Aplicação

Python 101

Condições

Blocos de código

scripts.py

Editor?

True or False?
work = True

#  'if work == True:' would also work
if work is True:
    print "Working"
else:
    print "Not working"

 

A nossa primeira condição

Remember booleans?

True or False?

A nossa primeira condição

Text

x = 10
work = True

True == False
3 < 2
x >= 10
not x < 10

#  'if work == True:' would also work
if work is True:
    print "Working"
else:
    print "Not working"

Aplicação

Python 101

Inputs

Pedra-Papel-Tesoura

Inputs

x = raw_input("what is your name?")
# '123' // will always be string
x = input("what is your name?")
# 123... will try to deduce

Pedra-papel-tesoura

  • Lagarto-spock?

Ficheiros

# https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output

x = None
while not x:
    try:
        x = int(raw_input())
    except ValueError:
        print 'Invalid Number'

# ficheiros
# http://www.tutorialspoint.com/python/python_files_io.htm

# ficheiro sera criado se nao existir
f = open('test.txt', 'r+')  # r para leitura, w para escrita
for line in f:
    print line
f.write('\n mais esta linha')
f.seek(0, 0);
f.readline
# MUITO IMPORTANTE
f.close()

Aplicação

Python 101

Listas e Estruturas de Dados

Ciclos e iterações

Listas (arrays, whatever...)

a_list = []

number_list =[2, 3, 4, 5]

string_list = [

  "r",

  "rambo",

  "noddy",

  "pikachu"

]

mix_list = [3, "batman", 4.0]

 

  • Têm de ser inicializados com [] (com conteúdo ou não)
  • Podem ter mais que um tipo de elementos

Listas - Métodos

  • Aceder e alterar um elemento
  • Adicionar um elemento
    • No final (append)
    • No início (prepend)
  • Remover um elemento
  • Ordenar elementos
Ciclos e Listas

For... in?

# a nice and "clean" list of fruits
fruits = [
    "raspberry",
    "strawberry",
    "melon",
    "batman"
]

# the classic loop
for fruit in fruits:
    # each time, this block content will be run
    # with each of the fruits as fruit
    print fruit
Ciclos e Listas

Métodos

# a nice and "clean" list of fruits
fruits = [
    "raspberry",
    "strawberry",
    "melon",
    "batman"
]

print len(fruits)

print fruits[0]
fruits.sort()
print fruits[0]
enumerate(fruits)
Ciclos e Listas

For... in?

# REMEMBER, FOR was made for LISTS
# (also known as foreach in other languages)
# but what if, instead of seeing it as an iterator that is increased,
# we think of all numbers [1..10]

# remember

for i in [1:10:1]:
    print i # for (int i=0; i< 10; i++){ ... }

for i in [1:10:2]:
    print i # for (int i=0; i< 10; i=i+2){ ... }

# however, range() is more common


# regular for loops
range(6)
range(1, 7)
range(0, 8, 2)

Dicionários

# key : value pair
# keys are unique
# values are not
settings = {
    "difficulty": 3,
    "nrLives": 3,
    "startingLevel": 1,
    "canCheat": False,
    "specialPowersAllowed": ["teleportation", "flying", "fireballs"]
}

print settings["nrLives"]

settings["nrLives"] = 50

print settings["nrLives"]


# ITERATE through items and keys
for key in settings:
    print "the option %s is set to %s " % (key, settings[key])

Aplicação

Python 101

Funções

Base

# parametros com valor por defeito
def adicao(x, y=0):
    return x + y

adicao(1, 3)
adicao(3) # sim, funciona

Outro Exemplo

fruits = ["banana", "lemon", "apple", "orange", "batman"]

# fruits.sort()    # how will it work if there are different types there?

for fruit in fruits:
    # each item in the list will now be known as fruits
    print "I would like a %s" % fruit

def eat_fruits(fruits):

    return [fruit + " eaten" for fruit in fruits]

print eat_fruits(fruits)

Uma função que retorne uma lista de frutas terminada em " eaten"

def eat_fruits(fruits):

    return [fruit + " eaten" for fruit in fruits]

print eat_fruits(fruits)
[
    "banana",
    "apple",
    "batman"
]

# tem de passar a...

[
    "banana eaten",
    "apple eaten",
    "batman eaten"
]

Importar funções de outros scripts?

from fruitlib import eat_fruits

eat_fruits(["banana", "apple"])

Criei eat_fruits em fruitlib.py

Lambda?

sum = lambda x, y: x + y
sum(9, 1)

'''
same as
'''
def sum_also(x, y):
    return x + y

What do we need this for?

Nothing. Good luck with JavaScript!

Aplicação

Python 101

Extras

Turtle

import turtle

# fonte: http://openbookproject.net/thinkcs/python/english3e/hello_little_turtles.html

wn = turtle.Screen()
wn.bgcolor("lightgreen")      # Set the window background color
wn.title("Hello, Tess!")      # Set the window title

tess = turtle.Turtle()
tess.color("blue")            # Tell tess to change her color
tess.pensize(3)               # Tell tess to set her pen width
tess.shape("turtle")

tess.forward(50)
tess.left(120)
tess.forward(50)

wn.mainloop()
import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.shape("turtle")
tess.color("blue")

tess.penup()                # This is new
size = 20
for i in range(30):
   tess.stamp()             # Leave an impression on the canvas
   size = size + 3          # Increase the size on every iteration
   tess.forward(size)       # Move tess along
   tess.right(24)           #  ...  and turn her

wn.mainloop()

Aplicação

Python 101

Classes

# http://www.tutorialspoint.com/python/python_classes_objects.htm
class Employee:
   'Common base class for all employees'
   empCount = 0

   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):
     print "Total Employee %d" % Employee.empCount

   def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
# http://www.tutorialspoint.com/python/python_classes_objects.htm
# "This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
# "This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
# http://www.tutorialspoint.com/python/python_classes_objects.htm
hasattr(emp1, 'age')    # Returns true if 'age' attribute exists
getattr(emp1, 'age')    # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age')    # Delete attribute 'age'
A escrever em pt?
#!/usr/bin/python
# -*- coding: utf-8 -*-

Python 101

By Miguel Costa

Python 101

Introdução ao Python - Contexto das Linguagens multi-paradigma

  • 437