You are on page 1of 6

Guia Rpido de Python

From OLPC
Contents
1 Comentrios
2 Imprimir na tela
3 Variveis
4 Strings
5 The 'While' Loop
6 Conditional Statements 'If'
7 The 'For' Loop
8 Funes
9 Tuples
10 Lists
11 Dictionaries
12 Mdulos
13 Referncias
Comentrios
# I am a comment.
Imprimir na tela
# em linhas diferentes
print Hello World!!!
print Hi!!!
# na mesma linha
print Hello World!!!,
print Hi!!!
Variveis
No precisa declarar antes de usar
O tipo de varivel ser o primeiro que for usado. Assim, se for usado uma string, a varivel ser do tipo string
v = 1
print "The value of v is now", v
v = v + 1
print "v now equals itself plus one, making it worth", v
Strings
# Para usar
word1 = "Good"
# Imprimir na mesma linha com espao
print word1, word2
# Concatenar
sentence = word1 + " " + word2 + " " +word3
The 'While' Loop
A indentao obrigatria
a = 0
while a < 10:
a = a + 1
print a
Conditional Statements 'If'
if a > 5:
print "Big number!"
elif a % 2 != 0:
print "This is an odd number"
else:
print "this number isn't greater than 5"
- elif desempenha o mesmo papel do else if da linguagem C.
The 'For' Loop
newList = [45, 'eat me', 90210, "The day has come, the walrus said, \
to speak of many things", -67]
for value in newList:
print value
word = raw_input("Who do you go for? ")
for letter in word:
call = "Gimme a " + letter + "!"
print call
A \ serve para indicar que a declarao continua na outra linha.
Funes
# Input: serve para pegar uma entrada do usurio
mult1 = input("Multiply this: ")
# Definir uma funo
def funnyfunction(first_word,second_word,third_word):
print "The word created is: " + first_word + second_word + third_word
return first_word + second_word + third_word
def add(a,b):
print a, "+", b, "=", a + b
# Usar uma funo
sentence = funnyfunction(a, na, nova)
add(input("Add this: "),input("to this: "))
Tuples
So listas, s que no se pode alterar seus valores.
months = ('January','February','March','April','May','June',\
'July','August','September','October','November',' December')
Lists
So listas de valores que podem ser alterados.
# Criar uma List
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
# Imprimir elemento especfico
print cats[2]
# Adicionar um novo item a List
cats.append('Catherine')
# Deletar um item da List
del cats[1]
Dictionaries
Tem-se um 'index' de palavras e para uma delas uma definio. In python, a palavra chamada de 'key' e a definio de 'value'.
# Criar um Dictionary
phonebook = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}
# Adicionar uma nova entrada no Dictionary
phonebook['Gingerbread Man'] = 1234567
# Deletar uma entrada do Dictionary
del phonebook['Andrew Parson']
# Criar um Dictionary vazio
ages = {}
# in: retorna verdadeiro se existe o key-name no dictionary
if 'Sue' in ages:
print "Sue is in the dictionary. She is", \
ages['Sue'], "years old"
# keys(): retorna uma lista com todos os nomes das keys
print "The following people are in the dictionary:"
print ages.keys()
# values(): retorna uma lista de todos os values
print "People are aged the following:", \
ages.values()
# Colocar em uma List (assim voc pode reordenar)
keys = ages.keys()
values = ages.values()
# Reordenao em uma List
keys.sort()
values.sort()
# len(): retorna o nmero de entradas do dictionary
print "The dictionary has", \
len(ages), "entries in it"
Mdulos
um arquivo python que contm s definies de variveis, funes e classes. Exemplo:
numberone = 1
ageofqueen = 78
def printhello():
print "hello"
def timesfour(input):
translate
print input * 4
class Piano:
def __init__(self):
self.type = raw_input("What type of piano? ")
self.height = raw_input("What height (in feet)? ")
self.price = raw_input("How much did it cost? ")
self.age = raw_input("How old is it (in years)? ")
def printdetails(self):
print "This piano is a/an " + self.height + " foot",
print self.type, "piano, " + self.age, "years old and costing\
" + self.price + " dollars."
Importar um mdulo completo: colocar no programa principal, desde que o mdulo esteja na mesma pasta do arquivo ou
venha com o python
import moduletest
Importar objetos individuais de um mdulo
from moduletest import ageofqueen
from moduletest import printhello
Usar mdulo completo
print moduletest.ageofqueen
cfcpiano = moduletest.Piano()
cfcpiano.printdetails()
Usar objetos individuais do mdulo
print ageofqueen
printhello()
Referncias
www.sthurlow.com/python (http://www.sthurlow.com/python)
Guia Rapido de PyGTK
Retrieved from "http://wiki.laptop.org/go/Guia_R%C3%A1pido_de_Python"
Categories: HowTo | Python | Developers
Developers
HowTo
Projects > Software > Programming language > Python
Personal tools
Log in
Login with OpenID
Search
Wiki search
About OLPC
The OLPC Wiki
Contact us
Blog
Communicate
Participate
laptop.org
About the laptop
Specifications
Buying
Help using
Support for
Upgrading
Repairing
Disassembly
About the tablet
Specifications
Buying
Help using
Support for
Projects
for Educators
for Developers
Software
Hardware
Activities
Deployment Guide
School Server (XS)
School Server (XSCE)
OLPC wiki
Recent changes
Glossary
Random page
Help using the wiki
Toolbox
What links here
Related changes
Special pages
Printable version
Permanent link
Last edited on 10:49, 26 February 2010.
Content is licensed under Creative Commons Attribution 2.5
One Laptop per Child

Hosted by Gossamer Threads

Contact us: help@laptop.org

You might also like