Skip to content

Instantly share code, notes, and snippets.

@alienbogart
Created September 15, 2018 13:57
Show Gist options
  • Save alienbogart/228c1a6321f413cc1c0e415d198a7d33 to your computer and use it in GitHub Desktop.
Save alienbogart/228c1a6321f413cc1c0e415d198a7d33 to your computer and use it in GitHub Desktop.

Table of Contents

  1. Variables
  2. Decisions
  3. Functions
  4. Lists
    1. Definition
    2. len() e .append
    3. get
    4. Find the last item in the list:
    5. Search
    6. Show the index position of a list item
  5. Loops
    1. While Loop, Exemplo
    2. For Loop, Exemplo
    3. Loop counters
  6. Objects
    1. __init__
    2. __str__()
  7. OOP

Variables

Ao contrário do C, Python não requer declaração de variável.

  • a = 3: cria uma variável do tipo inteiro

  • a = 3.0: cria uma variável do tipo float.

  • message = 'Hello word': cria uma variável to tipo string.

  • Create variable message and print it afterwards:

    message = "Hello world" print(message)

  • I can use "" to escape ', and ' to escape "

Case methods:

name = "ada lovelace"
print(name.title())
| Ada Lovelace
print(name.upper())
| ADA LOVELACE
print(name.lower())
| ada lovelace


user_input = input("Type some text: ")
print(user_input)

# Pode ser simplificado:

print(input("Type some text: "))

Decisions

Operator Type Purpose
= assignment assign value
== comparison checks if equal
!= comparison checks if not equal
> comparison greater than
>= comparison greater or equal
< comparison less than
<= comparison less or equal

Functions

  • function(): function call syntax
  • function(variable.method()): method call syntax

A função diga_ola recebe um único argumento, "nome", e ela encaixa no chamado da função print()

def diga_ola(name):
    print("Olá, " + name)

nome_usuario = input("Qual é o seu nome?? ")

diga_ola(nome_usuario)

Lists

Definition

Lists are ordered and may contain duplicates.

  • students = ['John', 'Jack', 'Ashton', 'Loretta']: list syntax
  • print(students): print the entire list

len() e .append

my_list = ['A', 'B', 'C']
len(my_list)
| 3
my_list.append('D')
len(my_list)
| 4
>>>

get

my_list = ['A', 'B', 'C', 'D']
my_list[0]
| 'A'

Find the last item in the list:

my_list = ['A', 'B', 'C', 'D']
last_position = len(my_list) - 1
my_list[last_position]
| 'D'

Search

2 in [1, 2, 3]
| True
2 in [1,2,3]
True
| 2 in [1, 2, 3]
True
5 in [1, 2, 3]
| False
'A' in ['A', 'B', 'C']
| True
1 in ['A', 'B', 'C']
| False
'D' in ['A', 'B', 'C']
| False

Show the index position of a list item

my_list = ['John', 'Jack', 'Ashton', 'Loretta']
my_list.index('Ashton')
| 2

It throws an error if the item does not occur:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
    my_list.index('Buffalo')
ValueError: 'Buffalo' is not in list

Loops

  • while loop: faça algo até eu dizer "para".
  • for loop: faça algo um número x de vezes.-

While Loop, Exemplo

Este loop vai adicionar um item à lista favoritos enquanto input_usuario for diferente de uma string vazia, imprimindo a lista em seguida.

favoritos = [] # cria uma lista vazia
mais_itens = True

while mais_itens:
    input_usuario = input("Digite algo de que gosta: ")
    if input_usuario == '':
        mais_itens = False
    else:
        favoritos.append(input_usuario)

    print("Essas são as coisas das quais você gosta!")
    print(favoritos)

For Loop, Exemplo

O for loop realiza uma tarefa para cada item de uma coleção.

  • for-each-loop sintaxe: for <item> in <variável>

A função imprimir_sem_ordem irá imprimir o caractere * seguido da transformação em string da variável item, que será dada pelo parâmetro to_print.

def imprimir_sem_ordem(to_print):
    for item in to_print:
        print("* " + str(item))

favoritos = [] # cria uma lista vazia
mais_itens = True

while mais_itens:
    input_usuario = input("Digite algo de que gosta: ")
    if input_usuario == '':
        mais_itens = False
    else:
        favoritos.append(input_usuario)

    print("Essas são as coisas das quais você gosta!")
    imprimir_sem_ordem(favoritos)

Loop counters

Servem para rodar um comando um determinado número de vezes.

def imprimir_sem_ordem(to_print):
    for item in to_print:
        print("* " + str(item))

favoritos = [] # cria uma lista vazia
mais_itens = True

while mais_itens:
    input_usuario = input("Digite algo de que gosta: ")
    if input_usuario == '':
        mais_itens = False
    else:
        favoritos.append(input_usuario)

    print("Essas são as coisas das quais você gosta!")
    imprimir_sem_ordem(favoritos)

Objects

Um container que armazena um ou mais valores, definido por uma classe.

code

# initializes the Person class

class Person:
    age = 15
    name = "Rolf"
    favorite_foods = ['beets', 'turnips', 'weisswurst']

    def birth_year():
        return 2018 - age

# create three new objects based in the Person class

    people = [Person(), Person(), Person()]

# initialize <sum>, creates the item <person> in the variable <people>, adds <person.age> to <sum> and stores it in <sum>.

sum = 0
for person in people:
    sum = sum + person.age


# prints the sum of the lengths in the variable <people> in string format.

print("The average age is: " + str(sum / len(people)))

__init__

Initialize objects in a more practical way.

# Initializes the Person class. The "self" keyword makes the initialized objects specific, not global.

class Person:
    def __init__(self, name, age, favorite_foods):
                 self.name = name
                 self.age = age
                 self.favorite_foods = favorite_foods

    def birth_yeah(self):
        return 2015 - self.age


# Create some people

people = [Person("Ed", 30, ["hotdogs", "jawbreakers"])
          , Person("Edd", 30, ["broccoli"])
          , Person("Eddy", 30, ["chunky puffs", "jawbreakers"])]

# add <person.age> to <age.sum> and the result of the function <person.birth_year()> to <year_sum> in each iteraction.

age_sum = 0
year_sum = 0
for person in people:
    age_sum = age_sum + person.age
    year_sum = year_sum + person.birth_year()

# print average age and average birth year.

print("The average age is: " +str(age_sum / len(people)))
print("The average birth year is: " + str(int(year_sum / len(people))))

__str__()

OOP

A class is a programming construct defined by the programmer to describe an object. An object is created when a class is instantiated. An object is an instance of a class.

  • Composition: when an object contains another object
  • Inheritance: when a class inherits behavior from another class
  • Parent class: the class from which the child inherits
  • Child class: the class that inherits from the parent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment