Guia Rápido de Python

From OLPC
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

  1. 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

  1. variables demonstrated

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"