Python
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()
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))
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)
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 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
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
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
Build a Translator:
def translate(phrase):
translation = ""
for letter in phrase:
if letter in "AEIOUaeiou":
translation = translation + "g"
else:
translation = translation + letter
return translation
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()