RESUMO-Python
RESUMO-Python
Python C++
Características principais
Simples e legível Rápido e requer uso explícito de recursos
Linguagem interpretada Linguagem compilada
Pode ser executada iterativamente Só executa após compilação completa
Especialmente concebida para desenvolvimento Especialmente concebida para desenvolvimento
rápido de protótipos e para tratamento de dados final de aplicativos com requisitos de tempo real
e/ou interfaces sem requisitos de tempo real. e/ou segurança de dados.
Sintaxe geral
Executa a partir do início Requer função main
Não exige declaração de variáveis Toda variável deve ser explicitamente declarada
Variáveis não tem tipo fixo Variáveis têm tipo declarado e invariável
Instruções são encerradas por \n Instruções são encerradas por ;
Instruções em 1 linha ou com \ no final Instruções podem ser multilinhas
Blocos são delimitados por : e indentação Blocos são delimitados por { ... }
Indentação é obrigatória Indentação é opcional, embora recomendável
Comentário de 1 linha com # Comentário de 1 linha com //
- Comentário de várias linhas com /* ... */
#include <iostream> // cout, endl
using namespace std;
int main() {
num_secreto = 42 int num_secreto = 42;
num_tentativas = 1 int num_tentativas = 1;
int palpite;
# Leh palpite como inteiro // Leh palpite como inteiro
cout << "Numero: ";
palpite = int(input("Numero: ")) cin >> palpite;
while palpite != num_secreto and \ while ((palpite != num_secreto) &&
num_tentativas < 5: (num_tentativas < 5)) {
print("Errado.") cout << "Errado. ";
cout << "Numero: ";
palpite = int(input("Numero: ")) cin >> palpite;
num_tentativas = num_tentativas+1 num_tentativas++;
}
if palpite == num_secreto: if (palpite == num_secreto) {
print("Correto") cout << "Correto" << endl;
}
else: else {
print("Incorreto. Fim.") cout << " Incorreto. Fim."
<< endl;
}
return 0;
}
Controle de fluxo
if condA: if (condA) {
foo1() foo1();
}
elif condB: else if (condB) {
foo2() foo2();
}
else: else {
foo3() foo3();
}
result = trueV if cond else falseV result = cond ? trueV : falseV;
Python C++
while cond: while (cond) {
foo() foo();
}
condition = True
while condition: do {
foo() foo();
condition = cond } while (cond);
for i in range(0, 10): for (int i=0; i<10; ++i) {
foo(i) foo(i);
}
for f in FooList: for (Foo f : FooList) {
foo(f) foo(f);
}
match pivot: switch (pivot) {
case 1: case 1:
foo() foo();
break;
case 2 | 3: case 2:
bar() case 3:
bar();
break;
case 4: case 4:
pass break;
case other: default:
ack() ack();
break;
}
Tipos
bool: True, False bool: true, false
int I [signed] int I;
short int, long int, long long int,
- unsigned short [int], unsigned [int],
unsigned long, unsigned long long
float X double X;
- float, long double
#include <complex>
complex C complex<double> C;
- char
- 's'
#include <string>
str S string S;
"Hello" """Hello""" "Hello"
'Hello' '''Hello'''
"Hello" " world" "Hello" + " world"
Variáveis e alocação de memória
int I = 5; // stack
auto I = 5; // stack
I = 5 // heap int* I = new int(5); // heap
int I, J;
-
I = J; // Cópia de valores
int *I, *J;
I = J I = J; // Cópia de endereços
X = 5
-
X = "Hello"
CONST_I = 5 // Cabe ao programador const int I = 5;
Criação de variável new
Variável deixa de existir ou del é chamado delete
None nullptr
Python C++
Operadores
5/3 double(5)/double(3) ou 5.0/3.0
5//3 5/3
5**3 pow(5,3)
not and or ! && ||
< > <= >= == != < > <= >= == !=
3 < x < 6 (3 < x) && (x < 6)
x, y, z = 3, 9, 5 x = 3;
y = 9;
z = 5;
+= -= *= /= %= += -= *= /= %=
- ++ --
Redefinir métodos: __add__ __sub__ Sobrecarga de operadores:
__mul__ __truediv__ __lt__ __le__ + - * / < <= > >= == != <<
__gt__ __ge__ __eq__ __ne__ __str__
Tipos multidados
- int A[10]; // stack
A = [1, 2, 3, 4, 5] // heap int A[] = {1, 2, 3, 4, 5}; // stack
# Pode alterar num elementos // Não pode alterar num elementos
B = [[1, 2, 3], [4, 5, 6]] int B[2][3] = { {1,2,3}, {4,5,6} };
# Pode alterar num elementos // Não pode alterar num elementos
A[0] A[0]
A[-1] -
#include <list>
#include <string>
N1 = ["Do", "Re", "Mi", "Fa", "Sol"] list<string> N1 =
{"Do", "Re", "Mi", "Fa", "Sol"};
N1[0] -
#include <vector>
#include <string>
N2 = ["Do", "Re", "Mi", "Fa", "Sol"] vector<string> N2 =
{"Do", "Re", "Mi", "Fa", "Sol"};
N2[0] N2[0]
N[2:4] -
N.append("La") N.push_back("La");
mixed = [1, "Two", 3.03, 4] -
mixed = [1, 2, [3,4], 5] -
len(N) N.size()
# set: { , } #include <set>
vogais = {"a", "e", "i", "o", "u"} set<char> vogais =
{'a','e','i','o','u'};
# dicionário: { : , : } #include <map>
itens = {23412: "Telha", map<int,string> itens = {
47902: "Tijolo", {23412,"Telha"},
4376: "Cimento", {47902,"Tijolo"},
197: "Areia"} {4376,"Cimento"},
{197,"Areia"} };
Funções
def soma(I, J=2): int soma(int I, int J=2) {
return I+J return I+J;
}
S = soma(2,3) int S = soma(2,3);
struct Result { int R1,R2; };
def func(I, J): Result func(int I, int J) {
return (2*I, J+3) return Result{2*I, J+3};
}
R1,R2 = func(2,3) Result R = func(2,3);
print(R1,R2) cout << R.R1 << R.R2;
Python C++
Classes
class C1: class C1 {
... ...
};
X = C1(3); C1 X(3);
self.◻ this->◻ ou ◻
class C1: class C1 {
def func(self): func() { ... }// Inline
... };
class C1 {
func();
};
-
C1::func() { // Não inline
...
}
class C1: class C1 {
public:
def __init__(self): C1() { // Construtor default
... ...
}
def __init__(self, I): C1(int I) { // Construtor
... ...
}
def __del__(self): ~C1() { // Destrutor
... ...
}
};
class C1: class C1 {
def __init__(self): public:
self.val = 5; int val=5;
};
class C1: class C1 {
public:
def __init__(self, I): int val;
self.val = I; C1(int I): val(I) {}
};
class C1:
def __init__(self):
self.V1 = 2;
self.__V2 = 3;
class C1: class C1 {
def __init__(self): public:
self.V1 = 2; int V1 = 2;
self.V2 = 3; private:
@property int V2 = 3;
def V2(self): };
return ◻ // Getter para V2
@V2.setter
def V2(self, new_V2):
V2 = ◻ // Setter para V2
class C1: class C1 {
public:
val = 3 static int val=3;
};
Python C++
class C1: class C1 {
@classmethod public:
def func(cls): // cls e não self static void func() { ... }
... };