Guia Rápido de Python

From OLPC
Revision as of 17:29, 3 May 2007 by Xavi (talk | contribs) (+categorization)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Comentários

# I am a comment.

Imprimir na tela

- em linhas diferentes

print “Hello World!!!”

print “Hi!!!”

- na mesma linha

print “Hello World!!!”,

print “Hi!!!”

Variáveis

- Não precisa declarar antes de usar

- O tipo de variável será o primeiro que for usado. Assim, se for usado uma string, a variável 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 espaço

print word1, word2

- Concatenar

sentence = word1 + " " + word2 + " " +word3

The 'While' Loop

- A indentação é obrigatória

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 “declaração” continua na outra linha.

Funções

- Input: serve para “pegar” uma entrada do usuário

mult1 = input("Multiply this: ")

- Definir uma função

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 função

sentence = funnyfunction(“a”, “na”, “nova”)

add(input("Add this: "),input("to this: "))

Tuples

- São listas, só que não se pode alterar seus valores.

months = ('January','February','March','April','May','June',\

'July','August','September','October','November',' December')

Lists

- São listas de valores que podem ser alterados.

- Criar uma List

cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']

- Imprimir elemento específico

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 definição. In python, a palavra é chamada de 'key' e a definição 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 = {}

- has_key(): retorna verdadeiro se existe o key-name no dictionary

if ages.has_key('Sue'):

   		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()

- Reordenação em uma List

keys.sort()

values.sort()

- len(): retorna o número de entradas do dictionary

print "The dictionary has", \

len(ages), "entries in it"

Módulos

- É um arquivo python que contêm só definições de variáveis, funções e classes.

- Exemplo:

numberone = 1

ageofqueen = 78

def printhello():

 		print "hello"
   	def timesfour(input):
   		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 módulo completo: colocar no programa principal, desde que o módulo esteja na mesma pasta do arquivo ou venha com o python

import moduletest

- Importar objetos individuais de um módulo

from moduletest import ageofqueen

from moduletest import printhello

- Usar módulo completo

print moduletest.ageofqueen

cfcpiano = moduletest.Piano()

cfcpiano.printdetails()

- Usar objetos individuais do módulo

print ageofqueen

printhello()

Referências

www.sthurlow.com/python