0% found this document useful (0 votes)
26 views

Python

Uploaded by

Ricardo Ferreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Python

Uploaded by

Ricardo Ferreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

PYTHON | Learning for Beginners

https://www.youtube.com/watch?v=rfscVS0vtbw (Pycharm + Python)

Índice
Variáveis, Tipos de Data e Printing............................................................................2
Input, Operations e Conversions................................................................................3
Variáveis, Tipos de Data e Printing
(A) Printing:
Barra superior – Run – Run... or press play button.
Print: escrever alguma coisa
print("Hello my name is " + character_name + " and I am " +
character_age + " years old,")
Strings: “Ricardo”
Numbers: 50.743984
Values: True/False
character_name = "Ricardo"
character_age = 50.985483
isMale = True

(B) Variáveis:
Python
x = 5
y = "John"
print(x)
print(y)
Nomes
character_name = "George"
character_age = "70"
Multiplas
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Globais
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

(C) Tipos de Data:


Input, Operações e Conversões

Getting input from a user:


name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! You are " + age)
Results:
Enter your name: Ricardo
Enter your age: 20
Hello Ricardo! You are 20

Operations

- Exemplo: my_num = 5
print(3 * (5 + 8))
10 a dividir por 3, o que sobra 1 (3+3+3=9)
print(10 % 3)
Variável
my_num = 5
print(my_num)
Print a number next to a string
print(str(my_num) + " my favourite number.")
|-5|= 5
print(abs(my_num))

Expoente (4 elevado a 6 = 4096)


print(pow(4, 6))
Máximo(32)/Mínimo(4)
print(max(4, 32))
print(min(4, 32))
Arredondamentos
print(round(3.7))
Usar mais expressões
from math import *
Arredondar para baixo sempre/Arredondar para cima sempre
print(floor(3.7))
print(ceil(3.7))
Raiz quadrada
print(sqrt(36))
Working with strings:
- Exemplo: Giraffe Academy
Parágrafo:
print("Giraffe\nAcademy")
Frases:
phrase = "Giraffe Academy"
print(phrase + " is cool!")
Maiúsculas/Minúsculas:
print(phrase.lower())
print(phrase.upper())
print(phrase.upper().isupper())
Length of the string:
print(len(phrase))
Letra 0: G – 01234567 8 910111213141516
print(phrase[0])
Encontrar palavras/letras:
print(phrase.index("Academy"))
Substituir palavras:
print(phrase.replace("Giraffe", "Elephant"))

Basic Calculator:
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = int(num1) + int(num2)

print (result)
int (apenas para números naturais)
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
result = float(num1) + float(num2)

print (result)
float (pode ter décimas)

Mad libs game:


{} = shif + alt + 8/9
color = input("Enter a color: ")
Plural_Noun = input("Enter a plural noun: ")
Celebrity = input("Enter a celebrity: ")

print("Roses are " + color)


print(Plural_Noun + " is blue")
print("I love " + Celebrity)
Results:
Enter a color: Green
Enter a plural noun: Sporting
Enter a celebrity: Bruno de Carvalho
Roses are Green
Sporting is blue
I love Bruno de Carvalho
Lists:
[] to store a bunch of values
friends = ["Rui", "Maria", "Bernardo"]
0 1 2 (Indexs)
friends = ["Rui", "Maria", "Bernardo"]
-3 -2 -1
print(friends [2])
print(friends [0:])
['Rui', 'Maria', 'Bernardo', 'Tiago', 'Dinis']
print(friends [0:3])
['Rui', 'Maria', 'Bernardo']
friends[1] = "Rui"
['Rui', 'Rui', 'Bernardo']

List Functions:
friends = ["Rui", "Maria", "Bernardo", "Tiago", "Dinis"]
lucky_numbers = [2, 4, 65, 34, 76, 86, 53]
friends.extend(lucky_numbers)
print(friends [0:])
['Rui', 'Maria', 'Bernardo', 'Tiago', 'Dinis', 2, 4, 65, 34, 76, 86, 53]
Adicionar um elemento à lista
friends.append("João")
Inserir um elemento num determinado lugar da lista
friends.insert(1, "João")
Remover elemento da lista
friends.remove("Maria")
Remover todos os elementos da lista
friends.clear()
Remove o último elemento da lista
friends.pop()
Verificar se determinado elemento pertence à lista
print(friends.index("Maria"))
Contar quantos elementos iguais existem na lista
print(friends.count("Maria"))
Ordenar por ordem alfabética
friends.sort()
Reverter
lucky_numbers.reverse()
Copiar uma lista
friends2 = friends.copy()

Tuples:
coordinates = (4, 8)
print(coordinates [1])
coordinates = [(4, 8), (4, 8), (49, 38)]

Funções:
def sayhi():
print("Hello User")
Calling the function:
sayhi()

- Examples:
def sayhi(name, age):
print("Hello User " + name + ", you are " + age)

sayhi("Ricardo", "35")
sayhi("João", "65")
sayhi("Steve", "43")
ou
def sayhi(name, age):
print("Hello User " + name + ", you are " + str(age))

sayhi("Ricardo", 35)
sayhi("João", 65)
sayhi("Steve", 43)

Return Statement:
def cube(num):
return num*num*num

print(cube(4))
Result: 64
Ou
def cube(num):
return num*num*num

result = (cube(4))
print(result)

If Statements:
1. One statement can be True or False.
is_male = True

if is_male:
print("You are a male")
Result: You are a male.
is_male = False

if is_male:
print("You are a male")
Result: none
2. Otherwise.
is_male = True

if is_male:
print("You are a male")
else:
print("You are not a male")
Result: You are a male.
is_male = False

if is_male:
print("You are a male")
else:
print("You are not a male")
Result: You are not a male.
3. Or
is_male = True
is_tall = True

if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You neither male nor tall")
Result: You are a male or tall or both
is_male = False
is_tall = False

if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You neither male nor tall")
Result: You neither male nor tall
4. And
is_male = True
is_tall = True

if is_male and is_tall:


print("You are a tall male")
else:
print("You are either not male or not tall or both")
Result: You are a tall made

5. Elif command and Not command


is_male = True
is_tall = False
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("You are not male but you are tall")
else:
print("You are either not male or not tall")
Result: You are a short male.
is_male = False
is_tall = True

if is_male and is_tall:


print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
print("You are not male but you are tall")
else:
print("You are either not male or not tall")
Result: You are not male, but you are tall.

If statements & comparisons:


def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3

print(max_num(80, 45, 5))


Result: 80
Comparison operators: == or >= or <= or != (inequal) or < or > .

Building a better Calculator:


num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))

if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
else:
print("Invalid operator")
Result: 705
Enter first number: 23.5
Enter operator: *
Enter second number: 30
Dictionary
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
}

print(monthConversions["Feb"])
Result: February
Or
monthConversions = {
"Jan": "January",
"Feb": "February",
"Mar": "March",
"Apr": "April",
"May": "May",
"Jun": "June",
"Jul": "July",
}

print(monthConversions.get("Feb"))

While Loop
i = 1
while i <= 10:
print(i)
i += 1

print("Done with loop")


Result:
1 2 3 4 5 6 7 8 9 10
Done with loop

Building guessing game:


secret_word = "giraffe"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False

while guess != secret_word and not(out_of_guesses):


if guess_count < guess_limit:
guess = input("Enter guess: ")
guess_count += 1
else:
out_of_guesses = True

if out_of_guesses:
print("Out of guesses, YOU LOSE!")
else:
print ("You win!")

For Loops:
Por cada letra numa palavra:
for letter in "Giraffe Academy":
print(letter)
Result: G I R A F F E A C A D E M Y
Ou
friends = ["Rui", "Maria", "Bernardo"]
for names in friends:
print(names)
Result: Rui Maria Bernardo

Lista de números até 10:


for index in range(10):
print(index)
Result: 0 1 2 3 4 5 6 7 8 9
Ou
for index in range(3, 10):
print(index)
Result: 3 4 5 6 7 8 9
Ou
for index in range(len(friends)):
print(friends[index])
Result: Rui, Maria, João
Ou
for index in range(5):
if index == 0:
print("First Iteration")
else:
print("Not first")
Result: First Iteration, Not first, Not first, Not first, Not first

Exponent Functions:
print(2**3)
Result: 2*2*2 = 8

Base/Expoente
def raise_to_power(base_num, pow_num):
result = 1
for index in range(pow_num):
result = result * base_num
return result

print(raise_to_power(2, 3))
Result: 8

2D & Nested Loops:


2D
number_grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0]
]
print(number_grid[0][3])
Result: 4
Nested Loops
number_grid = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 0]
]

for row in number_grid:


print(row)
Result:
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 0]
for row in number_grid:
for col in row:
print(col)
Result: 1 2 3 4 5 6 7 8 9 0

Build a Translator:
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation

print(translate(input("Enter a phrase: ")))


Result: dog = dgg
Ou
def translate(phrase):
translation = ""
for letter in phrase:
if letter.lower() in "aeiou":
if letter.isupper():
translation = translation + "G"
else:
translation = translation + "g"
else:
translation = translation + letter
return translation

print(translate(input("Enter a phrase: ")))


Result: Dog = Dgg
Comments
print("Comments are fun")
# This prints out a string
Ou
""""
bhfnjedhrfnjed
fnjekdm
frnemdri
"""

Try Except
try:
number = int(input("Enter a number: "))
print(number)
except:
print("Invalid Input")

try:
value = 10 / 0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError:
print("Divided by zero")
except ValueError:
print(("invalid input"))
Result: divided by zero.
Print the error
try:
answer = 10/0
number = int(input("Enter a number: "))
print(number)
except ZeroDivisionError as err:
print(err)
except ValueError:
print(("invalid input"))

Read Files
Read
open("employees", "r")
Write
open("employees", "w")
Edit information
open("employees", "a")
Read and write
open("employees", "r+")
Read files
employee_file = open("employees", "r")

print(employee_file.readable())

employee_file.close()
Result: True
employee_file = open("employees", "r")

print(employee_file.read())

employee_file.close()
Result: Jim - Salesman
Dwight - Salesman
Pan – Receptionist
Read Lines:
employee_file = open("employees", "r")

print(employee_file.readline())
print(employee_file.readline())

employee_file.close()
Result: Jim - Salesman
Dwight - Salesman
Ou
print(employee_file.readlines())
Result: ['Jim - Salesman\n', 'Dwight - Salesman\n', 'Pan - Receptionist']
Ou
print(employee_file.readlines()[1])
Result: Jim – Salesman
Ou
employee_file = open("employees", "r")
for employee in employee_file.readlines():
print(employee)
employee_file.close()
Result: Result: Jim - Salesman
Dwight - Salesman
Pan – Receptionist
Writing to Files:
Write
employee_file = open("employees", "a")

employee_file.write("Ricardo - Boss")

employee_file.close()
Adicionar parágrafo:
employee_file = open("employees", "a")

employee_file.write("\nKelly - Striper")

employee_file.close()
Overwriting
employee_file = open("employees", "w")

employee_file.write("\nKelly - Striper")

employee_file.close()
Criar um novo ficheiro:
employee_file = open("employees1", "w")

employee_file.write("\nKelly - Striper")

employee_file.close()
Ou
employee_file = open("index.html", "w")

employee_file.write("<p>This is HTML</>")

employee_file.close()

Modules and Pipes:


BEAUTIFUL SOUP 4 | Learning for Beginners
From bs4 import BeautifulSoup

You might also like