Diferență între revizuiri ale paginii „Lab 1”
| (Nu s-au afișat 2 versiuni intermediare efectuate de același utilizator) | |||
| Linia 21: | Linia 21: | ||
Throughout this laboratory, equivalent or similar C/C++ and Python code will be presented side by side. | Throughout this laboratory, equivalent or similar C/C++ and Python code will be presented side by side. | ||
| − | + | __TOC__ | |
== 1. Running a Python program == | == 1. Running a Python program == | ||
| Linia 31: | Linia 31: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
| Linia 38: | Linia 39: | ||
std::cout << "Hello, world!\n"; | std::cout << "Hello, world!\n"; | ||
return 0; | return 0; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | print("Hello, world!") </syntaxhighlight> | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | print("Hello, world!") | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 69: | Linia 73: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
| Linia 76: | Linia 81: | ||
std::cout << "Program started\n"; | std::cout << "Program started\n"; | ||
| − | + | ||
return 0; | return 0; | ||
| − | |||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
def main(): | def main(): | ||
| − | print("Program started") | + | print("Program started") |
| − | if | + | |
| − | main() </syntaxhighlight> | + | if __name__ == "__main__": |
| + | main() | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 98: | Linia 106: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
if (x > 10) { | if (x > 10) { | ||
| Linia 126: | Linia 132: | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
if x > 10: | if x > 10: | ||
| − | print("Large") | + | print("Large") |
</syntaxhighlight> | </syntaxhighlight> | ||
| Linia 252: | Linia 258: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
const double PI = 3.1415926535; | const double PI = 3.1415926535; | ||
| − | const int MAX_USERS = 100; </syntaxhighlight> | + | const int MAX_USERS = 100; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
PI = 3.1415926535 | PI = 3.1415926535 | ||
| − | MAX_USERS = 100 </syntaxhighlight> | + | MAX_USERS = 100 |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 272: | Linia 282: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
int a = 10; | int a = 10; | ||
int b = 3; | int b = 3; | ||
| Linia 280: | Linia 291: | ||
int prod = a * b; | int prod = a * b; | ||
int div = a / b; | int div = a / b; | ||
| − | int rem = a % b; </syntaxhighlight> | + | int rem = a % b; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
a = 10 | a = 10 | ||
b = 3 | b = 3 | ||
| Linia 289: | Linia 302: | ||
prod = a * b | prod = a * b | ||
div = a // b | div = a // b | ||
| − | rem = a % b </syntaxhighlight> | + | rem = a % b |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 298: | Linia 312: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
int a = 10; | int a = 10; | ||
int b = 3; | int b = 3; | ||
| − | std::cout << a / b; // 3 </syntaxhighlight> | + | std::cout << a / b; // 3 |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
a = 10 | a = 10 | ||
b = 3 | b = 3 | ||
print(a / b) # 3.3333333333333335 | print(a / b) # 3.3333333333333335 | ||
| − | print(a // b) # 3 </syntaxhighlight> | + | print(a // b) # 3 |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 321: | Linia 339: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
#include <cmath> | #include <cmath> | ||
| − | double result = std::pow(2, 8); </syntaxhighlight> | + | double result = std::pow(2, 8); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | result = 2 ** 8 </syntaxhighlight> | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | result = 2 ** 8 | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 337: | Linia 359: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
std::string name = "Alice"; | std::string name = "Alice"; | ||
int age = 21; | int age = 21; | ||
| Linia 344: | Linia 367: | ||
<< " is " | << " is " | ||
<< age | << age | ||
| − | << " years old\n"; </syntaxhighlight> | + | << " years old\n"; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
name = "Alice" | name = "Alice" | ||
age = 21 | age = 21 | ||
| − | print(name, "is", age, "years old") </syntaxhighlight> | + | print(name, "is", age, "years old") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 358: | Linia 384: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
std::cout << "Temperature: " | std::cout << "Temperature: " | ||
<< temperature | << temperature | ||
| − | << " C\n"; </syntaxhighlight> | + | << " C\n"; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | print(f"Temperature: {temperature} C") </syntaxhighlight> | + | | |
| − | |} | + | <syntaxhighlight lang="python"> |
| + | print(f"Temperature: {temperature} C") | ||
| + | </syntaxhighlight> | ||
| + | |} | ||
Expressions can appear directly inside an f-string: | Expressions can appear directly inside an f-string: | ||
| Linia 372: | Linia 402: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
std::cout << "Result: " | std::cout << "Result: " | ||
<< a + b | << a + b | ||
| − | << "\n"; </syntaxhighlight> | + | << "\n"; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | print(f"Result: {a + b}") </syntaxhighlight> | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | print(f"Result: {a + b}") | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 390: | Linia 424: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
int age; | int age; | ||
std::cout << "Age: "; | std::cout << "Age: "; | ||
| − | std::cin >> age; </syntaxhighlight> | + | std::cin >> age; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | age = int(input("Age: ")) </syntaxhighlight> | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | age = int(input("Age: ")) | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 413: | Linia 451: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
int a = std::stoi(text); | int a = std::stoi(text); | ||
| − | double b = std::stod(text); </syntaxhighlight> | + | double b = std::stod(text); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
a = int(text) | a = int(text) | ||
| − | b = float(text) </syntaxhighlight> | + | b = float(text) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 429: | Linia 471: | ||
! style="width:50%;" | Python | ! style="width:50%;" | Python | ||
|- | |- | ||
| − | | <syntaxhighlight lang="cpp"> | + | | |
| + | <syntaxhighlight lang="cpp"> | ||
if (temperature > 30) { | if (temperature > 30) { | ||
std::cout << "Hot\n"; | std::cout << "Hot\n"; | ||
| Linia 438: | Linia 481: | ||
else { | else { | ||
std::cout << "Cold\n"; | std::cout << "Cold\n"; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
if temperature > 30: | if temperature > 30: | ||
| − | print("Hot") | + | print("Hot") |
elif temperature > 20: | elif temperature > 20: | ||
| − | print("Warm") | + | print("Warm") |
else: | else: | ||
| − | print("Cold") </syntaxhighlight> | + | print("Cold") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 464: | Linia 510: | ||
Python uses words instead of the C/C++ symbolic logical operators. | Python uses words instead of the C/C++ symbolic logical operators. | ||
| − | {| class="wikitable" style="width:100%;" | + | {| class="wikitable" style="width:100%; table-layout:fixed;" |
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | <code>&&</code> |
| − | | <code>&&</code> | + | | <code>and</code> |
| − | | <code>and</code> | + | |- |
| − | | - | + | | <code>||</code> |
| − | | <code> | + | | <code>or</code> |
| − | | <code>or</code> | + | |- |
| − | | - | + | | <code>!</code> |
| − | | <code>!</code> | + | | <code>not</code> |
| − | | <code>not</code> | + | |} |
| − | | } | ||
For example: | For example: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
if (age >= 18 && enabled) { | if (age >= 18 && enabled) { | ||
| Linia 494: | Linia 537: | ||
if (!enabled) { | if (!enabled) { | ||
| − | ... | + | ... |
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
if age >= 18 and enabled: | if age >= 18 and enabled: | ||
| − | ... | + | ... |
if not enabled: | if not enabled: | ||
| − | ... </syntaxhighlight> | + | ... |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 511: | Linia 557: | ||
! Operation | ! Operation | ||
! C/C++ | ! C/C++ | ||
| − | + | ! Python | |
| − | + | |- | |
| − | | - | + | | equality |
| − | | equality | + | | <code>==</code> |
| − | | <code>==</code> | + | | <code>==</code> |
| − | | <code>==</code> | + | |- |
| − | | - | + | | inequality |
| − | | inequality | + | | <code>!=</code> |
| − | | <code>!=</code> | + | | <code>!=</code> |
| − | | <code>!=</code> | + | |- |
| − | | - | + | | less than |
| − | | less than | + | | <code><</code> |
| − | | <code> | + | | <code><</code> |
| − | | <code> | + | |- |
| − | | - | + | | greater than |
| − | | greater than | + | | <code>></code> |
| − | | <code> | + | | <code>></code> |
| − | | <code> | + | |- |
| − | | - | + | | less than or equal |
| − | | less than or equal | + | | <code><=</code> |
| − | | <code> | + | | <code><=</code> |
| − | | <code> | + | |- |
| − | | - | + | | greater than or equal |
| − | | greater than or equal | + | | <code>>=</code> |
| − | | <code> | + | | <code>>=</code> |
| − | | <code> | + | |} |
| − | | } | ||
Python also allows chained comparisons. | Python also allows chained comparisons. | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
if (0 <= x && x < 100) { | if (0 <= x && x < 100) { | ||
| Linia 565: | Linia 608: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
int maximum = (a > b) ? a : b; | int maximum = (a > b) ? a : b; | ||
| Linia 591: | Linia 632: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
int i = 0; | int i = 0; | ||
| Linia 603: | Linia 642: | ||
std::cout << i << "\n"; | std::cout << i << "\n"; | ||
i++; | i++; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
i = 0 | i = 0 | ||
while i < 5: | while i < 5: | ||
| − | print(i) | + | print(i) |
| − | i += 1 </syntaxhighlight> | + | i += 1 |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 631: | Linia 673: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
for (int i = 0; i < 5; i++) { | for (int i = 0; i < 5; i++) { | ||
| Linia 658: | Linia 698: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
for (int i = 2; i < 10; i++) { | for (int i = 2; i < 10; i++) { | ||
| Linia 679: | Linia 717: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
for (int i = 0; i < 10; i += 2) { | for (int i = 0; i < 10; i += 2) { | ||
| Linia 704: | Linia 740: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> values = {10, 20, 30}; | std::vector<int> values = {10, 20, 30}; | ||
| Linia 715: | Linia 749: | ||
for (size_t i = 0; i < values.size(); i++) { | for (size_t i = 0; i < values.size(); i++) { | ||
std::cout << values[i] << "\n"; | std::cout << values[i] << "\n"; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = [10, 20, 30] | values = [10, 20, 30] | ||
for i in range(len(values)): | for i in range(len(values)): | ||
| − | print(values[i]) </syntaxhighlight> | + | print(values[i]) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 728: | Linia 765: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> values = {10, 20, 30}; | std::vector<int> values = {10, 20, 30}; | ||
| Linia 739: | Linia 774: | ||
for (const auto& value : values) { | for (const auto& value : values) { | ||
std::cout << value << "\n"; | std::cout << value << "\n"; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = [10, 20, 30] | values = [10, 20, 30] | ||
for value in values: | for value in values: | ||
| − | print(value) </syntaxhighlight> | + | print(value) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 756: | Linia 794: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<std::string> names = { | std::vector<std::string> names = { | ||
| Linia 774: | Linia 810: | ||
<< names[i] | << names[i] | ||
<< "\n"; | << "\n"; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
names = ["Ana", "Bob", "Carol"] | names = ["Ana", "Bob", "Carol"] | ||
for i, name in enumerate(names): | for i, name in enumerate(names): | ||
| − | print(i, ":", name) </syntaxhighlight> | + | print(i, ":", name) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 789: | Linia 828: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> values = { | std::vector<int> values = { | ||
| Linia 803: | Linia 840: | ||
std::cout << values[0]; | std::cout << values[0]; | ||
| − | std::cout << values.size(); </syntaxhighlight> | + | std::cout << values.size(); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = [10, 20, 30] | values = [10, 20, 30] | ||
| Linia 810: | Linia 849: | ||
print(values[0]) | print(values[0]) | ||
| − | print(len(values)) </syntaxhighlight> | + | print(len(values)) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 816: | Linia 856: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
// A normal std::vector cannot | // A normal std::vector cannot | ||
| Linia 828: | Linia 866: | ||
std::vector<int> values = { | std::vector<int> values = { | ||
10, 20, 30 | 10, 20, 30 | ||
| − | }; </syntaxhighlight> | + | }; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = [ | values = [ | ||
10, | 10, | ||
| Linia 835: | Linia 875: | ||
"hello", | "hello", | ||
True | True | ||
| − | ] </syntaxhighlight> | + | ] |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 845: | Linia 886: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> v = {10, 20, 30, 40}; | std::vector<int> v = {10, 20, 30, 40}; | ||
std::cout << v[v.size() - 1]; // 40 | std::cout << v[v.size() - 1]; // 40 | ||
| − | std::cout << v[v.size() - 2]; // 30 </syntaxhighlight> | + | std::cout << v[v.size() - 2]; // 30 |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
v = [10, 20, 30, 40] | v = [10, 20, 30, 40] | ||
print(v[-1]) # 40 | print(v[-1]) # 40 | ||
| − | print(v[-2]) # 30 </syntaxhighlight> | + | print(v[-2]) # 30 |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 868: | Linia 910: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> v = { | std::vector<int> v = { | ||
| Linia 882: | Linia 922: | ||
v.begin() + 1, | v.begin() + 1, | ||
v.begin() + 4 | v.begin() + 4 | ||
| − | ); </syntaxhighlight> | + | ); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
v = [10, 20, 30, 40, 50] | v = [10, 20, 30, 40, 50] | ||
| − | part = v[1:4] </syntaxhighlight> | + | part = v[1:4] |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 904: | Linia 947: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
// Requires an explicit loop or | // Requires an explicit loop or | ||
| Linia 922: | Linia 963: | ||
print(v[3:]) # [3, 4, 5] | print(v[3:]) # [3, 4, 5] | ||
print(v[::2]) # [0, 2, 4] | print(v[::2]) # [0, 2, 4] | ||
| − | print(v[::-1]) # [5, 4, 3, 2, 1, 0] </syntaxhighlight> | + | print(v[::-1]) # [5, 4, 3, 2, 1, 0] |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 930: | Linia 972: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> values = {10, 20, 30}; | std::vector<int> values = {10, 20, 30}; | ||
| Linia 945: | Linia 985: | ||
) != values.end()) { | ) != values.end()) { | ||
std::cout << "Found\n"; | std::cout << "Found\n"; | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | values = [10, 20, 30] | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | values = [10, 20, 30] | ||
if 20 in values: | if 20 in values: | ||
| − | print("Found") </syntaxhighlight> | + | print("Found") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 965: | Linia 1.008: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_map<std::string, int> grades; | std::unordered_map<std::string, int> grades; | ||
| Linia 977: | Linia 1.018: | ||
grades["Bob"] = 8; | grades["Bob"] = 8; | ||
| − | std::cout << grades["Ana"]; </syntaxhighlight> | + | std::cout << grades["Ana"]; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
grades = {} | grades = {} | ||
| Linia 984: | Linia 1.027: | ||
grades["Bob"] = 8 | grades["Bob"] = 8 | ||
| − | print(grades["Ana"]) </syntaxhighlight> | + | print(grades["Ana"]) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 990: | Linia 1.034: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_map<std::string, int> grades = { | std::unordered_map<std::string, int> grades = { | ||
| Linia 1.016: | Linia 1.058: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
for (const auto& [name, grade] : grades) { | for (const auto& [name, grade] : grades) { | ||
| Linia 1.042: | Linia 1.082: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_set<int> values = { | std::unordered_set<int> values = { | ||
| Linia 1.057: | Linia 1.095: | ||
if (20 != values.end()) { | if (20 != values.end()) { | ||
// conceptually test membership | // conceptually test membership | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = {10, 20, 30} | values = {10, 20, 30} | ||
| Linia 1.064: | Linia 1.104: | ||
if 20 in values: | if 20 in values: | ||
| − | print("Found") </syntaxhighlight> | + | print("Found") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.086: | Linia 1.127: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::tuple<int, double, std::string> data { | std::tuple<int, double, std::string> data { | ||
| Linia 1.112: | Linia 1.151: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
int add(int a, int b) | int add(int a, int b) | ||
| Linia 1.124: | Linia 1.161: | ||
} | } | ||
| − | int result = add(2, 3); </syntaxhighlight> | + | int result = add(2, 3); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
def add(a, b): | def add(a, b): | ||
| − | return a + b | + | return a + b |
| − | result = add(2, 3) </syntaxhighlight> | + | |
| + | result = add(2, 3) | ||
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.137: | Linia 1.178: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
double average( | double average( | ||
| Linia 1.175: | Linia 1.214: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
void greet( | void greet( | ||
| Linia 1.191: | Linia 1.228: | ||
greet(); | greet(); | ||
| − | greet("Alice"); </syntaxhighlight> | + | greet("Alice"); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
def greet(name="World"): | def greet(name="World"): | ||
| − | print(f"Hello, {name}") | + | print(f"Hello, {name}") |
| + | |||
greet() | greet() | ||
| − | greet("Alice") </syntaxhighlight> | + | greet("Alice") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.205: | Linia 1.246: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
void connect( | void connect( | ||
| Linia 1.218: | Linia 1.257: | ||
); | ); | ||
| − | connect("server.local", 443, true); </syntaxhighlight> | + | connect("server.local", 443, true); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
def connect(host, port, secure): | def connect(host, port, secure): | ||
| − | ... | + | ... |
| + | |||
connect( | connect( | ||
| − | host="server.local", | + | host="server.local", |
| − | port=443, | + | port=443, |
| − | secure=True | + | secure=True |
| − | ) </syntaxhighlight> | + | ) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.239: | Linia 1.282: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::pair<int, int> minmax(int a, int b) | std::pair<int, int> minmax(int a, int b) | ||
| Linia 1.251: | Linia 1.292: | ||
return {a, b}; | return {a, b}; | ||
| − | + | ||
return {b, a}; | return {b, a}; | ||
| − | |||
} | } | ||
| − | auto [minimum, maximum] = minmax(10, 3); </syntaxhighlight> | + | auto [minimum, maximum] = minmax(10, 3); |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
def minmax(a, b): | def minmax(a, b): | ||
| − | if a < b: | + | if a < b: |
| − | return a, b | + | return a, b |
| − | + | return b, a | |
| − | return b, a | ||
| − | |||
| − | minimum, maximum = minmax(10, 3) </syntaxhighlight> | + | |
| − | |} | + | minimum, maximum = minmax(10, 3) |
| + | </syntaxhighlight> | ||
| + | |} | ||
This is another example of tuple unpacking. | This is another example of tuple unpacking. | ||
| Linia 1.279: | Linia 1.321: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
int temp = a; | int temp = a; | ||
| Linia 1.301: | Linia 1.341: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::string text = "Hello"; | std::string text = "Hello"; | ||
std::cout << text.size(); | std::cout << text.size(); | ||
| − | std::cout << text[0]; </syntaxhighlight> | + | std::cout << text[0]; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
text = "Hello" | text = "Hello" | ||
print(len(text)) | print(len(text)) | ||
| − | print(text[0]) </syntaxhighlight> | + | print(text[0]) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.322: | Linia 1.363: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::string first = "Hello"; | std::string first = "Hello"; | ||
| Linia 1.333: | Linia 1.372: | ||
std::string result = | std::string result = | ||
| − | first + " " + second; </syntaxhighlight> | + | first + " " + second; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
first = "Hello" | first = "Hello" | ||
second = "World" | second = "World" | ||
| − | result = first + " " + second </syntaxhighlight> | + | result = first + " " + second |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.344: | Linia 1.386: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::string text = "hello"; | std::string text = "hello"; | ||
| Linia 1.355: | Linia 1.395: | ||
// Usually requires algorithms, | // Usually requires algorithms, | ||
// explicit transformations, | // explicit transformations, | ||
| − | // or utility functions. </syntaxhighlight> | + | // or utility functions. |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
text = "hello" | text = "hello" | ||
| Linia 1.363: | Linia 1.405: | ||
print(text.startswith("he")) | print(text.startswith("he")) | ||
print(text.endswith("lo")) | print(text.endswith("lo")) | ||
| − | print(text.replace("l", "x")) </syntaxhighlight> | + | print(text.replace("l", "x")) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.375: | Linia 1.418: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> a = {1, 2, 3}; | std::vector<int> a = {1, 2, 3}; | ||
| Linia 1.389: | Linia 1.430: | ||
std::cout << a[0]; // 1 | std::cout << a[0]; // 1 | ||
| − | std::cout << b[0]; // 100 </syntaxhighlight> | + | std::cout << b[0]; // 100 |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
a = [1, 2, 3] | a = [1, 2, 3] | ||
| Linia 1.398: | Linia 1.441: | ||
print(a[0]) # 100 | print(a[0]) # 100 | ||
| − | print(b[0]) # 100 </syntaxhighlight> | + | print(b[0]) # 100 |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.425: | Linia 1.469: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> b = a; | std::vector<int> b = a; | ||
| Linia 1.456: | Linia 1.498: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> a = {1, 2, 3}; | std::vector<int> a = {1, 2, 3}; | ||
| Linia 1.469: | Linia 1.509: | ||
// Address comparison would be needed | // Address comparison would be needed | ||
| − | // to determine object identity. </syntaxhighlight> | + | // to determine object identity. |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| − | a = [1, 2, 3] | + | | |
| + | <syntaxhighlight lang="python"> | ||
| + | a = [1, 2, 3] | ||
b = [1, 2, 3] | b = [1, 2, 3] | ||
print(a == b) # True | print(a == b) # True | ||
| − | print(a is b) # False </syntaxhighlight> | + | print(a is b) # False |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.499: | Linia 1.542: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
Object* ptr = nullptr; | Object* ptr = nullptr; | ||
| Linia 1.510: | Linia 1.551: | ||
if (ptr == nullptr) { | if (ptr == nullptr) { | ||
... | ... | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
value = None | value = None | ||
if value is None: | if value is None: | ||
| − | ... </syntaxhighlight> | + | ... |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.523: | Linia 1.567: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
try { | try { | ||
| Linia 1.555: | Linia 1.597: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python — direct translation | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> squares; | std::vector<int> squares; | ||
| Linia 1.566: | Linia 1.606: | ||
for (int i = 0; i < 10; i++) { | for (int i = 0; i < 10; i++) { | ||
squares.push_back(i * i); | squares.push_back(i * i); | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
squares = [] | squares = [] | ||
for i in range(10): | for i in range(10): | ||
| − | squares.append(i * i) </syntaxhighlight> | + | squares.append(i * i) |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.579: | Linia 1.622: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python — idiomatic | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> squares; | std::vector<int> squares; | ||
| Linia 1.590: | Linia 1.631: | ||
for (int i = 0; i < 10; i++) { | for (int i = 0; i < 10; i++) { | ||
squares.push_back(i * i); | squares.push_back(i * i); | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
squares = [ | squares = [ | ||
i * i | i * i | ||
for i in range(10) | for i in range(10) | ||
| − | ] </syntaxhighlight> | + | ] |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.601: | Linia 1.645: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> squares; | std::vector<int> squares; | ||
| Linia 1.614: | Linia 1.656: | ||
squares.push_back(i * i); | squares.push_back(i * i); | ||
} | } | ||
| − | } </syntaxhighlight> | + | } |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
squares = [ | squares = [ | ||
i * i | i * i | ||
for i in range(10) | for i in range(10) | ||
if i % 2 == 0 | if i % 2 == 0 | ||
| − | ] </syntaxhighlight> | + | ] |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.634: | Linia 1.679: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
| Linia 1.654: | Linia 1.697: | ||
}; | }; | ||
| − | + | ||
double sum = 0.0; | double sum = 0.0; | ||
| Linia 1.677: | Linia 1.720: | ||
return 0; | return 0; | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
} | } | ||
| − | + | </syntaxhighlight> | |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
| + | grades = { | ||
| + | "Ana": 9.5, | ||
| + | "Bob": 7.0, | ||
| + | "Carol": 8.5, | ||
| + | "Dan": 6.0, | ||
| + | } | ||
| + | |||
average = sum(grades.values()) / len(grades) | average = sum(grades.values()) / len(grades) | ||
| Linia 1.693: | Linia 1.737: | ||
for name, grade in grades.items(): | for name, grade in grades.items(): | ||
| − | if grade >= average: | + | if grade >= average: |
| − | print(f"{name}: {grade}") </syntaxhighlight> | + | print(f"{name}: {grade}") |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.712: | Linia 1.757: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
| Linia 1.728: | Linia 1.771: | ||
}; | }; | ||
| − | + | ||
int sum = 0; | int sum = 0; | ||
int count = 0; | int count = 0; | ||
| Linia 1.748: | Linia 1.791: | ||
return 0; | return 0; | ||
| − | |||
| − | } </syntaxhighlight> | + | } |
| + | </syntaxhighlight> | ||
| | | | ||
'''Your implementation:''' | '''Your implementation:''' | ||
| Linia 1.766: | Linia 1.809: | ||
# reads a sequence of integer values; | # reads a sequence of integer values; | ||
| − | |||
# stores them in a list; | # stores them in a list; | ||
| − | |||
# prints the minimum value; | # prints the minimum value; | ||
| − | |||
# prints the maximum value; | # prints the maximum value; | ||
| − | |||
# prints the average; | # prints the average; | ||
| − | |||
# prints how many values are above the average. | # prints how many values are above the average. | ||
| Linia 1.780: | Linia 1.818: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::vector<int> values; | std::vector<int> values; | ||
| Linia 1.793: | Linia 1.829: | ||
int minimum = ...; | int minimum = ...; | ||
int maximum = ...; | int maximum = ...; | ||
| − | double average = ...; </syntaxhighlight> | + | double average = ...; |
| − | | <syntaxhighlight lang="python"> | + | </syntaxhighlight> |
| + | | | ||
| + | <syntaxhighlight lang="python"> | ||
values = [] | values = [] | ||
| Linia 1.801: | Linia 1.839: | ||
minimum = ... | minimum = ... | ||
maximum = ... | maximum = ... | ||
| − | average = ... </syntaxhighlight> | + | average = ... |
| + | </syntaxhighlight> | ||
|} | |} | ||
| Linia 1.836: | Linia 1.875: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_map<std::string, int> | std::unordered_map<std::string, int> | ||
| Linia 1.873: | Linia 1.910: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_set<int> unique_values; | std::unordered_set<int> unique_values; | ||
| Linia 1.891: | Linia 1.926: | ||
# using an explicit loop; | # using an explicit loop; | ||
| − | |||
# using Python's built-in functionality. | # using Python's built-in functionality. | ||
| Linia 1.906: | Linia 1.940: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ | + | ! style="width:50%;" | C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="cpp"> | <syntaxhighlight lang="cpp"> | ||
std::unordered_map<std::string, double> | std::unordered_map<std::string, double> | ||
| Linia 2.007: | Linia 2.039: | ||
{| class="wikitable" style="width:100%;" | {| class="wikitable" style="width:100%;" | ||
| − | ! C/C++ habit | + | ! style="width:50%;" | C/C++ habit |
| − | + | ! style="width:50%;" | Typical Python approach | |
| − | | | + | |- |
| − | | - | + | | Iterate using an integer index |
| − | | Iterate using an integer index | + | | Iterate directly over the objects |
| − | | Iterate directly over the objects | + | |- |
| − | | - | + | | Manually maintain counters |
| − | | Manually maintain counters | + | | Consider <code>enumerate()</code> |
| − | | Consider <code>enumerate()</code> | + | |- |
| − | | - | + | | Search manually through a container |
| − | | Search manually through a container | + | | Use <code>in</code> |
| − | | Use <code>in</code> | + | |- |
| − | | - | + | | Manually calculate container size |
| − | | Manually calculate container size | + | | Use <code>len()</code> |
| − | | Use <code>len()</code> | + | |- |
| − | | - | + | | Explicit temporary variable for swapping |
| − | | Explicit temporary variable for swapping | + | | Use tuple unpacking |
| − | | Use tuple unpacking | + | |- |
| − | | - | + | | Explicit loop for simple transformations |
| − | | Explicit loop for simple transformations | + | | Consider a comprehension |
| − | | Consider a comprehension | + | |- |
| − | | - | + | | Long output expressions |
| − | | Long output expressions | + | | Use f-strings |
| − | | Use f-strings | + | |- |
| − | | - | + | | Copy assumed after assignment |
| − | | Copy assumed after assignment | + | | Remember that names refer to objects |
| − | | Remember that names refer to objects | + | |- |
| − | | - | + | | Check null using equality |
| − | | Check null using equality | + | | Use <code>is None</code> |
| − | | Use <code>is None</code> | + | |} |
| − | | } | ||
The objective is not simply to translate C/C++ syntax into Python syntax. | The objective is not simply to translate C/C++ syntax into Python syntax. | ||
| Linia 2.044: | Linia 2.075: | ||
{| class="wikitable" style="width:100%; table-layout:fixed;" | {| class="wikitable" style="width:100%; table-layout:fixed;" | ||
| − | ! C++ style translated literally | + | ! style="width:50%;" | C++ style translated literally |
| − | + | ! style="width:50%;" | More idiomatic Python | |
| − | | | + | |- |
| − | | - | + | | |
| − | | | ||
| − | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
for i in range(len(values)): | for i in range(len(values)): | ||
| Linia 2.069: | Linia 2.098: | ||
The main mappings introduced in this laboratory are: | The main mappings introduced in this laboratory are: | ||
| − | {| class="wikitable" | + | {| class="wikitable" style="width:100%;" |
| − | ! C/C++ | + | ! style="width:50%;" | C/C++ |
| − | + | ! style="width:50%;" | Python | |
| − | | | + | |- |
| − | | - | + | | <code>{ ... }</code> |
| − | | <code>{ ... }</code> | + | | indentation |
| − | | indentation | + | |- |
| − | | - | + | | <code>true</code>, <code>false</code> |
| − | | <code>true</code>, <code>false</code> | + | | <code>True</code>, <code>False</code> |
| − | | <code>True</code>, <code>False</code> | + | |- |
| − | | - | + | | <code>&&</code> |
| − | | <code>&&</code> | + | | <code>and</code> |
| − | | <code>and</code> | + | |- |
| − | | - | + | | <code>||</code> |
| − | | <code> | + | | <code>or</code> |
| − | | <code>or</code> | + | |- |
| − | | - | + | | <code>!</code> |
| − | | <code>!</code> | + | | <code>not</code> |
| − | | <code>not</code> | + | |- |
| − | | - | + | | <code>nullptr</code> |
| − | | <code>nullptr</code> | + | | <code>None</code> |
| − | | <code>None</code> | + | |- |
| − | | - | + | | <code>std::vector</code> |
| − | | <code>std::vector</code> | + | | <code>list</code> |
| − | | <code>list</code> | + | |- |
| − | | - | + | | <code>std::unordered_map</code> |
| − | | <code>std::unordered_map</code> | + | | <code>dict</code> |
| − | | <code>dict</code> | + | |- |
| − | | - | + | | <code>std::unordered_set</code> |
| − | | <code>std::unordered_set</code> | + | | <code>set</code> |
| − | | <code>set</code> | + | |- |
| − | | - | + | | <code>std::tuple</code> |
| − | | <code>std::tuple</code> | + | | <code>tuple</code> |
| − | | <code>tuple</code> | + | |- |
| − | | - | + | | <code>std::cout</code> |
| − | | <code>std::cout</code> | + | | <code>print()</code> |
| − | | <code>print()</code> | + | |- |
| − | | - | + | | <code>std::cin</code> |
| − | | <code>std::cin</code> | + | | <code>input()</code> |
| − | | <code>input()</code> | + | |- |
| − | | - | + | | indexed iteration |
| − | | indexed iteration | + | | direct iteration / <code>enumerate()</code> |
| − | | direct iteration / <code>enumerate()</code> | + | |- |
| − | | - | + | | manual search |
| − | | manual search | + | | <code>in</code> |
| − | | <code>in</code> | + | |- |
| − | | - | + | | <code>std::pow(a, b)</code> |
| − | | <code>std::pow(a, b)</code> | + | | <code>a ** b</code> |
| − | | <code>a ** b</code> | + | |- |
| − | | - | + | | integer division |
| − | | integer division | + | | <code>//</code> |
| − | | <code>//</code> | + | |} |
| − | | } | ||
The central idea to retain from this laboratory is: | The central idea to retain from this laboratory is: | ||
| Linia 2.134: | Linia 2.162: | ||
# complete all exercises from this laboratory; | # complete all exercises from this laboratory; | ||
| − | |||
# ensure Python 3 is installed; | # ensure Python 3 is installed; | ||
| − | |||
# create a virtual environment successfully; | # create a virtual environment successfully; | ||
| − | |||
# create a Git repository for the semester project; | # create a Git repository for the semester project; | ||
| − | |||
# become familiar with lists, dictionaries, tuples and sets; | # become familiar with lists, dictionaries, tuples and sets; | ||
| − | |||
# review the concepts of classes, objects, inheritance and composition from C++. | # review the concepts of classes, objects, inheritance and composition from C++. | ||
In '''Lab 2''', these concepts will be revisited from the perspective of Python's object model and Pythonic object-oriented programming. | In '''Lab 2''', these concepts will be revisited from the perspective of Python's object model and Pythonic object-oriented programming. | ||
Versiunea curentă din 14 septembrie 2026 05:51
Lab 1 — Python for C/C++ Programmers
Objectives
The purpose of this laboratory is to introduce Python to students who already have experience with procedural programming in C and object-oriented programming in C++.
The focus is therefore not on learning programming concepts from scratch, but on understanding how concepts already familiar from C/C++ are expressed in Python.
After completing this laboratory, you should be able to:
- understand the basic syntax of Python;
- recognize the main differences between Python and C/C++;
- work with Python's fundamental data types;
- use conditional statements and loops;
- work with lists, dictionaries, sets and tuples;
- define and call functions;
- understand basic Python object/reference semantics;
- recognize several common Python idioms;
- create and execute a simple Python project.
Throughout this laboratory, equivalent or similar C/C++ and Python code will be presented side by side.
1. Running a Python program
A C/C++ program normally has to be compiled before it is executed. Python programs are usually executed directly by the Python interpreter.
| C/C++ | Python |
|---|---|
#include <iostream>
int main()
{
std::cout << "Hello, world!\n";
return 0;
}
|
print("Hello, world!")
|
A Python source file normally uses the extension:
.py
For example:
hello.py
It can be executed using:
python3 hello.py
Unlike C/C++, Python does not require a special main() function.
However, larger Python programs commonly use:
| C/C++ | Python |
|---|---|
#include <iostream>
int main()
{
std::cout << "Program started\n";
return 0;
}
|
def main():
print("Program started")
if __name__ == "__main__":
main()
|
The Python version is not mandatory, but this pattern will become useful when programs are split into multiple modules.
2. Blocks and indentation
In C and C++, braces delimit blocks of code.
Python uses indentation instead.
| C/C++ | Python |
|---|---|
if (x > 10) {
std::cout << "Large\n";
std::cout << "Value: " << x << "\n";
}
|
if x > 10:
print("Large")
print("Value:", x)
|
Indentation in Python is part of the language syntax.
The standard convention is 4 spaces per indentation level.
For example, the following code is incorrect:
if x > 10:
print("Large")
Python will report an IndentationError.
3. Variables and types
C/C++ variables have a declared static type.
Python variables do not require explicit type declarations.
| C/C++ | Python |
|---|---|
int count = 10;
double temperature = 23.5;
bool enabled = true;
std::string name = "Alice";
|
count = 10
temperature = 23.5
enabled = True
name = "Alice"
|
Python is dynamically typed.
This means that a variable name can later refer to an object of another type.
| C/C++ | Python |
|---|---|
int value = 10;
// Not allowed:
// value = "hello";
|
value = 10
value = "hello"
|
This does not mean that Python has no types.
Objects still have types:
| C/C++ | Python |
|---|---|
#include <iostream>
#include <typeinfo>
int value = 10;
std::cout << typeid(value).name();
|
value = 10
print(type(value))
|
Python will produce:
<class 'int'>
Common basic types
| C/C++ type | Python equivalent | Example |
|---|---|---|
int
|
int
|
42
|
float / double
|
float
|
3.14
|
bool
|
bool
|
True, False
|
char
|
No separate character type | "A"
|
std::string
|
str
|
"Hello"
|
nullptr
|
None
|
None
|
4. Constants
C++ can enforce that a value cannot be modified using const.
Python does not enforce constants at language level.
| C/C++ | Python |
|---|---|
const double PI = 3.1415926535;
const int MAX_USERS = 100;
|
PI = 3.1415926535
MAX_USERS = 100
|
By convention, Python names that should be treated as constants are written using uppercase letters.
Nothing prevents the programmer from changing them.
5. Arithmetic operators
Most arithmetic operators are identical.
| C/C++ | Python |
|---|---|
int a = 10;
int b = 3;
int sum = a + b;
int diff = a - b;
int prod = a * b;
int div = a / b;
int rem = a % b;
|
a = 10
b = 3
sum_ = a + b
diff = a - b
prod = a * b
div = a // b
rem = a % b
|
There is an important difference between / and //.
| C/C++ | Python |
|---|---|
int a = 10;
int b = 3;
std::cout << a / b; // 3
|
a = 10
b = 3
print(a / b) # 3.3333333333333335
print(a // b) # 3
|
In C/C++, dividing two integers performs integer division.
In Python, the / operator always performs floating-point division, while // performs floor division.
Python also provides an exponentiation operator:
| C/C++ | Python |
|---|---|
#include <cmath>
double result = std::pow(2, 8);
|
result = 2 ** 8
|
6. Printing values
Output using std::cout is replaced by the built-in print() function.
| C/C++ | Python |
|---|---|
std::string name = "Alice";
int age = 21;
std::cout << name
<< " is "
<< age
<< " years old\n";
|
name = "Alice"
age = 21
print(name, "is", age, "years old")
|
Python also provides formatted string literals, commonly called f-strings.
| C/C++ | Python |
|---|---|
std::cout << "Temperature: "
<< temperature
<< " C\n";
|
print(f"Temperature: {temperature} C")
|
Expressions can appear directly inside an f-string:
| C/C++ | Python |
|---|---|
std::cout << "Result: "
<< a + b
<< "\n";
|
print(f"Result: {a + b}")
|
7. Reading input
Console input is performed using input().
An important difference is that input() always returns a string.
| C/C++ | Python |
|---|---|
int age;
std::cout << "Age: ";
std::cin >> age;
|
age = int(input("Age: "))
|
Without the conversion:
age = input("Age: ")
age is a string.
Conversions are explicit:
| C/C++ | Python |
|---|---|
int a = std::stoi(text);
double b = std::stod(text);
|
a = int(text)
b = float(text)
|
8. Conditional statements
The overall structure is similar, but Python does not use parentheses or braces.
| C/C++ | Python |
|---|---|
if (temperature > 30) {
std::cout << "Hot\n";
}
else if (temperature > 20) {
std::cout << "Warm\n";
}
else {
std::cout << "Cold\n";
}
|
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Warm")
else:
print("Cold")
|
Notice that Python uses:
elif
instead of:
else if
9. Boolean operators
Python uses words instead of the C/C++ symbolic logical operators.
| C/C++ | Python |
|---|---|
&&
|
and
|
||
|
or
|
!
|
not
|
For example:
| C/C++ | Python |
|---|---|
if (age >= 18 && enabled) {
...
}
if (!enabled) {
...
}
|
if age >= 18 and enabled:
...
if not enabled:
...
|
10. Comparison operators
Most comparison operators are identical.
| Operation | C/C++ | Python |
|---|---|---|
| equality | ==
|
==
|
| inequality | !=
|
!=
|
| less than | <
|
<
|
| greater than | >
|
>
|
| less than or equal | <=
|
<=
|
| greater than or equal | >=
|
>=
|
Python also allows chained comparisons.
| C/C++ | Python |
|---|---|
if (0 <= x && x < 100) {
...
}
|
if 0 <= x < 100:
...
|
11. The ternary operator
Both languages support conditional expressions.
| C/C++ | Python |
|---|---|
int maximum = (a > b) ? a : b;
|
maximum = a if a > b else b
|
Notice that Python's order is different:
value_if_true if condition else value_if_false
12. While loops
A while loop is very similar.
| C/C++ | Python |
|---|---|
int i = 0;
while (i < 5) {
std::cout << i << "\n";
i++;
}
|
i = 0
while i < 5:
print(i)
i += 1
|
Python does not have ++ or -- operators.
Therefore:
i += 1
is used instead.
13. For loops
This is one of the first important conceptual differences.
In C/C++, a for statement commonly controls a numeric index.
Python's for statement iterates over objects.
| C/C++ | Python |
|---|---|
for (int i = 0; i < 5; i++) {
std::cout << i << "\n";
}
|
for i in range(5):
print(i)
|
range(5) generates values conceptually equivalent to:
0, 1, 2, 3, 4
A different starting value can be specified:
| C/C++ | Python |
|---|---|
for (int i = 2; i < 10; i++) {
std::cout << i << "\n";
}
|
for i in range(2, 10):
print(i)
|
A step can also be specified:
| C/C++ | Python |
|---|---|
for (int i = 0; i < 10; i += 2) {
std::cout << i << "\n";
}
|
for i in range(0, 10, 2):
print(i)
|
14. Iterating over containers
Suppose we want to print every element of a vector/list.
An index-based implementation is possible:
| C/C++ | Python |
|---|---|
std::vector<int> values = {10, 20, 30};
for (size_t i = 0; i < values.size(); i++) {
std::cout << values[i] << "\n";
}
|
values = [10, 20, 30]
for i in range(len(values)):
print(values[i])
|
However, this is generally not the preferred Python style.
If the index is not required, iterate directly over the elements.
| C++ | Python |
|---|---|
std::vector<int> values = {10, 20, 30};
for (const auto& value : values) {
std::cout << value << "\n";
}
|
values = [10, 20, 30]
for value in values:
print(value)
|
The second Python version should normally be preferred.
15. When both index and value are required
C/C++ programmers frequently use an explicit index.
Python provides enumerate().
| C/C++ | Python |
|---|---|
std::vector<std::string> names = {
"Ana",
"Bob",
"Carol"
};
for (size_t i = 0; i < names.size(); i++) {
std::cout << i
<< ": "
<< names[i]
<< "\n";
}
|
names = ["Ana", "Bob", "Carol"]
for i, name in enumerate(names):
print(i, ":", name)
|
This introduces another frequently used Python feature: unpacking.
16. Lists
The closest commonly used Python equivalent to std::vector is list.
| C++ | Python |
|---|---|
std::vector<int> values = {
10, 20, 30
};
values.push_back(40);
std::cout << values[0];
std::cout << values.size();
|
values = [10, 20, 30]
values.append(40)
print(values[0])
print(len(values))
|
Python lists can contain objects of different types:
| C++ | Python |
|---|---|
// A normal std::vector cannot
// contain unrelated types.
std::vector<int> values = {
10, 20, 30
};
|
values = [
10,
3.14,
"hello",
True
]
|
Although Python allows this, homogeneous collections are generally easier to understand and maintain when the elements conceptually represent the same kind of data.
17. Negative indexing
Python allows indexing from the end of a sequence.
| C++ | Python |
|---|---|
std::vector<int> v = {10, 20, 30, 40};
std::cout << v[v.size() - 1]; // 40
std::cout << v[v.size() - 2]; // 30
|
v = [10, 20, 30, 40]
print(v[-1]) # 40
print(v[-2]) # 30
|
18. Slicing
Python sequences support slicing directly.
| C++ | Python |
|---|---|
std::vector<int> v = {
10, 20, 30, 40, 50
};
std::vector<int> part(
v.begin() + 1,
v.begin() + 4
);
|
v = [10, 20, 30, 40, 50]
part = v[1:4]
|
The result is:
[20, 30, 40]
General syntax:
sequence[start:stop:step]
For example:
| C/C++ | Python |
|---|---|
// Requires an explicit loop or
// another algorithm.
|
v = [0, 1, 2, 3, 4, 5]
print(v[1:4]) # [1, 2, 3]
print(v[:3]) # [0, 1, 2]
print(v[3:]) # [3, 4, 5]
print(v[::2]) # [0, 2, 4]
print(v[::-1]) # [5, 4, 3, 2, 1, 0]
|
19. Membership testing
Checking whether an element exists in a container is commonly performed using in.
| C++ | Python |
|---|---|
std::vector<int> values = {10, 20, 30};
if (std::find(
values.begin(),
values.end(),
20
) != values.end()) {
std::cout << "Found\n";
}
|
values = [10, 20, 30]
if 20 in values:
print("Found")
|
The opposite test uses not in:
if 100 not in values:
print("Not found")
20. Dictionaries
A Python dict is similar to a C++ associative container such as std::unordered_map.
| C++ | Python |
|---|---|
std::unordered_map<std::string, int> grades;
grades["Ana"] = 10;
grades["Bob"] = 8;
std::cout << grades["Ana"];
|
grades = {}
grades["Ana"] = 10
grades["Bob"] = 8
print(grades["Ana"])
|
A dictionary can also be initialized directly:
| C++ | Python |
|---|---|
std::unordered_map<std::string, int> grades = {
{"Ana", 10},
{"Bob", 8},
{"Carol", 9}
};
|
grades = {
"Ana": 10,
"Bob": 8,
"Carol": 9,
}
|
Iterating over keys and values:
| C++ | Python |
|---|---|
for (const auto& [name, grade] : grades) {
std::cout << name
<< ": "
<< grade
<< "\n";
}
|
for name, grade in grades.items():
print(name, ":", grade)
|
21. Sets
A Python set represents a collection containing unique values.
| C++ | Python |
|---|---|
std::unordered_set<int> values = {
10, 20, 30
};
values.insert(40);
if (20 != values.end()) {
// conceptually test membership
}
|
values = {10, 20, 30}
values.add(40)
if 20 in values:
print("Found")
|
A more correct C++ membership test would be:
if (values.find(20) != values.end()) {
std::cout << "Found\n";
}
Sets are particularly useful when:
- duplicate values should be removed;
- fast membership tests are required;
- mathematical set operations are useful.
22. Tuples
Tuples are similar to lists, but they are immutable.
| C++ | Python |
|---|---|
std::tuple<int, double, std::string> data {
10,
3.14,
"test"
};
|
data = (10, 3.14, "test")
|
Python uses tuples extensively for returning or unpacking multiple values.
23. Functions
Functions are declared using def.
| C/C++ | Python |
|---|---|
int add(int a, int b)
{
return a + b;
}
int result = add(2, 3);
|
def add(a, b):
return a + b
result = add(2, 3)
|
Python does not require parameter or return types to be declared.
However, Python supports optional type hints.
| C++ | Python |
|---|---|
double average(
double a,
double b
) {
return (a + b) / 2.0;
}
|
def average(
a: float,
b: float
) -> float:
return (a + b) / 2
|
Type hints do not normally enforce types at runtime.
They provide information for:
- the programmer;
- IDEs;
- static analysis tools;
- documentation.
24. Default parameters
Both C++ and Python support default parameter values.
| C++ | Python |
|---|---|
void greet(
const std::string& name = "World"
) {
std::cout << "Hello, "
<< name
<< "\n";
}
greet();
greet("Alice");
|
def greet(name="World"):
print(f"Hello, {name}")
greet()
greet("Alice")
|
25. Named arguments
Python allows function arguments to be specified by name.
| C++ | Python |
|---|---|
void connect(
std::string host,
int port,
bool secure
);
connect("server.local", 443, true);
|
def connect(host, port, secure):
...
connect(
host="server.local",
port=443,
secure=True
)
|
This can make calls with several parameters easier to understand.
26. Returning multiple values
In C++, multiple return values typically require a structure, tuple, pair or output parameters.
Python commonly uses tuples.
| C++ | Python |
|---|---|
std::pair<int, int> minmax(int a, int b)
{
if (a < b)
return {a, b};
return {b, a};
}
auto [minimum, maximum] = minmax(10, 3);
|
def minmax(a, b):
if a < b:
return a, b
return b, a
minimum, maximum = minmax(10, 3)
|
This is another example of tuple unpacking.
27. Swapping variables
A temporary variable is normally used in C.
Python supports unpacking directly.
| C/C++ | Python |
|---|---|
int temp = a;
a = b;
b = temp;
|
a, b = b, a
|
28. Strings
Python strings behave more like C++ std::string objects than traditional C character arrays.
| C++ | Python |
|---|---|
std::string text = "Hello";
std::cout << text.size();
std::cout << text[0];
|
text = "Hello"
print(len(text))
print(text[0])
|
String concatenation:
| C++ | Python |
|---|---|
std::string first = "Hello";
std::string second = "World";
std::string result =
first + " " + second;
|
first = "Hello"
second = "World"
result = first + " " + second
|
Python strings provide many built-in operations:
| C++ | Python |
|---|---|
std::string text = "hello";
// Usually requires algorithms,
// explicit transformations,
// or utility functions.
|
text = "hello"
print(text.upper())
print(text.lower())
print(text.startswith("he"))
print(text.endswith("lo"))
print(text.replace("l", "x"))
|
29. Lists versus arrays: important semantic difference
Consider assigning one collection to another.
With normal C++ value semantics, copying a vector produces another vector.
Python assignment behaves differently.
| C++ | Python |
|---|---|
std::vector<int> a = {1, 2, 3};
std::vector<int> b = a;
b[0] = 100;
std::cout << a[0]; // 1
std::cout << b[0]; // 100
|
a = [1, 2, 3]
b = a
b[0] = 100
print(a[0]) # 100
print(b[0]) # 100
|
This happens because:
b = a
does not copy the list.
Both names refer to the same list object.
Conceptually:
+-------------+
a ---> | [1, 2, 3] |
+-------------+
^
|
b --------+
To explicitly create a shallow copy:
| C++ | Python |
|---|---|
std::vector<int> b = a;
|
b = a.copy()
|
or:
b = list(a)
This distinction is extremely important when using Python.
30. Equality versus identity
Python distinguishes between:
- whether two objects contain equal values;
- whether two names refer to the exact same object.
| C++ | Python |
|---|---|
std::vector<int> a = {1, 2, 3};
std::vector<int> b = {1, 2, 3};
std::cout << (a == b); // true
// Address comparison would be needed
// to determine object identity.
|
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True
print(a is b) # False
|
In Python:
== tests value equality
is tests object identity
Do not use is when you intend to compare values.
A common correct use is:
if value is None:
...
31. None and nullptr
Python's None represents the absence of a value.
| C++ | Python |
|---|---|
Object* ptr = nullptr;
if (ptr == nullptr) {
...
}
|
value = None
if value is None:
...
|
32. Exceptions
Exception handling is conceptually similar.
| C++ | Python |
|---|---|
try {
int value = std::stoi(text);
}
catch (const std::exception& e) {
std::cout << "Invalid value\n";
}
|
try:
value = int(text)
except ValueError:
print("Invalid value")
|
Python generally uses exceptions rather than special error return values for many failure conditions.
33. A first Pythonic transformation
Consider creating a vector/list containing the squares of the numbers from 0 to 9.
A direct translation from C++ could look like this:
| C++ | Python — direct translation |
|---|---|
std::vector<int> squares;
for (int i = 0; i < 10; i++) {
squares.push_back(i * i);
}
|
squares = []
for i in range(10):
squares.append(i * i)
|
The Python code is correct.
However, Python provides a concise construct called a list comprehension.
| C++ | Python — idiomatic |
|---|---|
std::vector<int> squares;
for (int i = 0; i < 10; i++) {
squares.push_back(i * i);
}
|
squares = [
i * i
for i in range(10)
]
|
A condition can also be included.
| C++ | Python |
|---|---|
std::vector<int> squares;
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
squares.push_back(i * i);
}
}
|
squares = [
i * i
for i in range(10)
if i % 2 == 0
]
|
An important objective of this course is not only to write programs that work in Python, but to learn to write programs in a style appropriate for Python.
34. Example: processing student grades
Consider the following problem:
- store the grades of several students;
- compute the average;
- print the students whose grade is greater than or equal to the average.
| C++ | Python |
|---|---|
#include <iostream>
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, double> grades = {
{"Ana", 9.5},
{"Bob", 7.0},
{"Carol", 8.5},
{"Dan", 6.0}
};
double sum = 0.0;
for (const auto& [name, grade] : grades) {
sum += grade;
}
double average = sum / grades.size();
std::cout << "Average: "
<< average
<< "\n";
for (const auto& [name, grade] : grades) {
if (grade >= average) {
std::cout << name
<< ": "
<< grade
<< "\n";
}
}
return 0;
}
|
grades = {
"Ana": 9.5,
"Bob": 7.0,
"Carol": 8.5,
"Dan": 6.0,
}
average = sum(grades.values()) / len(grades)
print(f"Average: {average:.2f}")
for name, grade in grades.items():
if grade >= average:
print(f"{name}: {grade}")
|
Notice that the Python version uses existing language functionality rather than manually reproducing every operation.
In particular:
sum(grades.values())
expresses the intention directly.
35. Exercise 1 — Translation
Translate the following C++ program into Python.
| C++ | Python |
|---|---|
#include <iostream>
#include <vector>
int main()
{
std::vector<int> values = {
12, 7, 18, 3, 24, 11
};
int sum = 0;
int count = 0;
for (int value : values) {
if (value % 2 == 0) {
sum += value;
count++;
}
}
std::cout << "Count: "
<< count
<< "\n";
std::cout << "Sum: "
<< sum
<< "\n";
return 0;
}
|
Your implementation: # TODO
|
After implementing a direct translation, try to simplify the Python implementation.
36. Exercise 2 — Statistics
Write a Python program that:
- reads a sequence of integer values;
- stores them in a list;
- prints the minimum value;
- prints the maximum value;
- prints the average;
- prints how many values are above the average.
The equivalent C++ structure might begin as follows:
| C++ | Python |
|---|---|
std::vector<int> values;
// Read / initialize values.
int minimum = ...;
int maximum = ...;
double average = ...;
|
values = []
# Read / initialize values.
minimum = ...
maximum = ...
average = ...
|
Useful Python functions include:
len(...)
sum(...)
min(...)
max(...)
37. Exercise 3 — Word frequency
Given a sentence, count how many times each word occurs.
For example:
python is simple and python is powerful
should produce information equivalent to:
python -> 2
is -> 2
simple -> 1
and -> 1
powerful -> 1
A possible C++ data structure and its Python equivalent are:
| C++ | Python |
|---|---|
std::unordered_map<std::string, int>
frequencies;
|
frequencies = {}
|
Use:
sentence.split()
to separate the sentence into words.
38. Exercise 4 — Remove duplicates
Given:
values = [4, 2, 7, 4, 2, 9, 7, 1]
create a collection containing every distinct value.
Think about the following C++ and Python data structures:
| C++ | Python |
|---|---|
std::unordered_set<int> unique_values;
|
unique_values = set()
|
Try to solve the problem both:
- using an explicit loop;
- using Python's built-in functionality.
39. Exercise 5 — Small problem
Write a program that receives a list of students and their grades and determines:
- the class average;
- the student with the highest grade;
- all students who passed;
- all students whose grade is above the class average.
Suggested representation:
| C++ | Python |
|---|---|
std::unordered_map<std::string, double>
grades;
|
grades = {
"Ana": 9.5,
"Bob": 7.0,
"Carol": 8.5,
"Dan": 4.0,
}
|
Avoid using numeric indices unless an index is actually required.
40. Creating a project environment
Python applications commonly use a virtual environment to isolate project dependencies.
Create a directory for the project:
mkdir python-project
cd python-project
Create a virtual environment:
python3 -m venv .venv
Activate it on Linux/macOS:
source .venv/bin/activate
Activate it on Windows PowerShell:
.venv\Scripts\Activate.ps1
The command prompt will normally indicate that the environment is active.
For example:
(.venv) student@computer:~/python-project$
Packages installed using pip will now be installed inside this environment.
For example:
pip install requests
To inspect installed packages:
pip list
41. Recommended initial project structure
For the first laboratories, the following structure is sufficient:
python-project/
├── .venv/
├── main.py
├── README.md
└── .gitignore
A basic .gitignore should contain:
.venv/
__pycache__/
*.pyc
Do not commit the virtual environment to Git.
42. C/C++ habits to reconsider in Python
When transitioning from C/C++ to Python, the following patterns should generally be reconsidered.
| C/C++ habit | Typical Python approach |
|---|---|
| Iterate using an integer index | Iterate directly over the objects |
| Manually maintain counters | Consider enumerate()
|
| Search manually through a container | Use in
|
| Manually calculate container size | Use len()
|
| Explicit temporary variable for swapping | Use tuple unpacking |
| Explicit loop for simple transformations | Consider a comprehension |
| Long output expressions | Use f-strings |
| Copy assumed after assignment | Remember that names refer to objects |
| Check null using equality | Use is None
|
The objective is not simply to translate C/C++ syntax into Python syntax.
Consider:
| C++ style translated literally | More idiomatic Python |
|---|---|
for i in range(len(values)):
print(values[i])
|
for value in values:
print(value)
|
Both programs are correct.
The second expresses the programmer's intention more directly.
43. Summary
The main mappings introduced in this laboratory are:
| C/C++ | Python |
|---|---|
{ ... }
|
indentation |
true, false
|
True, False
|
&&
|
and
|
||
|
or
|
!
|
not
|
nullptr
|
None
|
std::vector
|
list
|
std::unordered_map
|
dict
|
std::unordered_set
|
set
|
std::tuple
|
tuple
|
std::cout
|
print()
|
std::cin
|
input()
|
| indexed iteration | direct iteration / enumerate()
|
| manual search | in
|
std::pow(a, b)
|
a ** b
|
| integer division | //
|
The central idea to retain from this laboratory is:
Python should not be treated merely as C++ with different syntax. Python provides its own abstractions and idioms, and using them generally produces simpler and more readable programs.
44. Preparation for Lab 2
Before the next laboratory:
- complete all exercises from this laboratory;
- ensure Python 3 is installed;
- create a virtual environment successfully;
- create a Git repository for the semester project;
- become familiar with lists, dictionaries, tuples and sets;
- review the concepts of classes, objects, inheritance and composition from C++.
In Lab 2, these concepts will be revisited from the perspective of Python's object model and Pythonic object-oriented programming.