From C++ to Python
A Developer’s Translation Guide
Python
C++
A Self-Contained Programming Guide
June 6, 2025
Master the transition from C++ to Python
Complete with syntax mappings, paradigm shifts,
and practical examples for developers
2
C++ to Python Guide
Table of Contents
Contents
1 Core Language Differences
2
1.1 Compiled vs. Interpreted . . . . . . . . . . . . . . . . . . . . . . . .
2
1.2 Static vs. Dynamic Typing . . . . . . . . . . . . . . . . . . . . . . .
2
1.3 Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . .
3
1.4 Syntax Philosophy . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
2 Basic Syntax and Operations
3
2.1 Variable Declaration and Basic Types . . . . . . . . . . . . . . . . .
3
2.1.1 C++ Approach . . . . . . . . . . . . . . . . . . . . . . . . .
3
2.1.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
4
2.2 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
2.3 Input and Output (I/O) . . . . . . . . . . . . . . . . . . . . . . . .
4
2.3.1 C++ Approach . . . . . . . . . . . . . . . . . . . . . . . . .
4
2.3.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
4
2.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
3 Control Structures
5
3.1 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . .
5
3.1.1 C++ Approach . . . . . . . . . . . . . . . . . . . . . . . . .
5
3.1.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
6
3.2 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
3.2.1 C++ Approach (Counter-based) . . . . . . . . . . . . . . . .
6
3.2.2 Python Equivalent (Using range) . . . . . . . . . . . . . . .
6
3.3 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
3.3.1 C++ Approach . . . . . . . . . . . . . . . . . . . . . . . . .
7
3.3.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
7
3.4 Absence of do-while and switch . . . . . . . . . . . . . . . . . . .
7
4 Functions and Recursion
7
4.1 Function Definition and Return Values . . . . . . . . . . . . . . . .
7
4.1.1 C++ Approach . . . . . . . . . . . . . . . . . . . . . . . . .
7
4.1.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
8
4.2 Parameter Passing . . . . . . . . . . . . . . . . . . . . . . . . . . .
8
4.2.1 C++ Example (By Value vs. By Reference) . . . . . . . . .
8
4.2.2 Python Equivalent . . . . . . . . . . . . . . . . . . . . . . .
9
4.3 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
9
4.3.1 C++ Recursive Factorial . . . . . . . . . . . . . . . . . . . .
9
4.3.2 Python Recursive Factorial . . . . . . . . . . . . . . . . . . .
9
5 Introduction to Python’s Core Data Structures
10
5.1 From Static Arrays to the Python list . . . . . . . . . . . . . . . . 10
5.1.1 C++ Array . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
5.1.2 Python list Equivalent . . . . . . . . . . . . . . . . . . . . 10
5.2 From std::string to the Python str . . . . . . . . . . . . . . . . 10
5.2.1 C++ std::string . . . . . . . . . . . . . . . . . . . . . . . 10
5.2.2 Python str Equivalent . . . . . . . . . . . . . . . . . . . . . 10
5.3 From struct to the Python dict . . . . . . . . . . . . . . . . . . . 11
5.3.1 C++ struct . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5.3.2 Python dict Equivalent . . . . . . . . . . . . . . . . . . . . 11
6 Deep Dive: The Python
list and
dict Guide
11
A Developer’s
Translation
6.1 The Python list: More Than an Array . . . . . . . . . . . . . . . 11
6.1.1 List Creation . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1
C++ to Python Guide
1
2
Core Language Differences
Key Information
Before translating code, it’s crucial to understand the fundamental philosophical
differences between C++ and Python. These differences explain why the syntax
and development process vary so significantly.
1.1
Compiled vs. Interpreted
▶ C++ is a compiled language. You write your source code (in .cpp files), and a
compiler translates it into a machine-code executable (.exe on Windows, or a binary
file on Linux/macOS). This executable is then run by the operating system. Errors
related to type mismatches are caught during this compilation step, before the program
ever runs.
▶ Python is an interpreted language. You write your source code (in .py files),
and the Python interpreter reads and executes the code line by line at runtime. There
is no separate compilation step. This allows for faster development cycles and more
interactive programming.
1.2
Static vs. Dynamic Typing
Important Note
This is the most significant difference you will encounter daily.
▶ C++ uses static typing. You must declare the data type of every variable before
you use it, and that type cannot be changed. The compiler enforces these rules.
C++ Code
1
2
int count = 10;
count = " hello " ;
// ’ count ’ is an integer , always .
// COMPILE ERROR !
▶ Python uses dynamic typing. You do not declare variable types. A variable is
simply a name that refers to an object. The type belongs to the object, not the variable
name. You can reassign a variable to an object of a different type at any time.
Python Code
1
2
count = 10
# ’ count ’ refers to an integer object .
count = " hello " # Perfectly valid . Now ’ count ’ refers to a string
object .
A Developer’s Translation Guide
C++ to Python Guide
1.3
3
Memory Management
▶ C++ requires manual memory management. For objects created on the heap,
you are responsible for allocating memory with new and deallocating it with delete.
Forgetting to deallocate memory leads to memory leaks.
▶ Python uses automatic memory management. Python’s garbage collector automatically tracks object usage and frees memory when an object is no longer referenced.
You do not use new or delete.
1.4
Syntax Philosophy
▶ C++ uses braces and semicolons. Code blocks (for functions, loops, conditionals)
are delimited by curly braces {}, and statements are terminated with a semicolon ;.
▶ Python uses indentation. Code blocks are defined by their level of indentation
(typically 4 spaces). The colon : is used to start a new indented block. This enforces
a clean, readable layout.
2
Basic Syntax and Operations
Key Information
This section maps the most fundamental C++ syntax to Python equivalents.
2.1
Variable Declaration and Basic Types
Key Concept
In C++, you declare a variable’s type. In Python, you just assign a value.
2.1.1 C++ Approach
C++ Code
int integer_var = 10;
double real_var = 3.14;
3 bool boolean_var = true ;
4 char char_var = ’A ’;
5 std :: string string_var = " Hello " ;
1
2
A Developer’s Translation Guide
C++ to Python Guide
4
2.1.2 Python Equivalent
Python Code
integer_var = 10
real_var = 3.14 # This is a ’ float ’ in Python
3 boolean_var = True
# Note the capital ’T ’
4 # There is no separate ’ char ’ type ; it ’s a string of length 1
5 char_var = ’A ’
6 string_var = " Hello "
1
2
2.2
Constants
• C++: const double PI = 3.14159;
• Python: PI = 3.14159 (The use of all-caps indicates to other programmers
that this value should not be changed).
2.3
Input and Output (I/O)
Important Note
Python’s I/O is simpler and requires explicit type casting for input.
2.3.1 C++ Approach
C++ Code
1
2
# include < iostream >
# include < string >
3
4
5
int age ;
std :: string name ;
6
std :: cout << " Enter your name : " ;
std :: getline ( std :: cin , name ) ;
9 std :: cout << " Enter your age : " ;
10 std :: cin >> age ;
7
8
11
12
std :: cout << " Hello , " << name << " ! You are " << age << " years old .
" << std :: endl ;
2.3.2 Python Equivalent
The input() function always returns a string. You must cast it to the desired type
(e.g., int()). F-strings are the modern, easy way to format output.
A Developer’s Translation Guide
C++ to Python Guide
5
Python Code
name = input ( " Enter your name : " )
age_str = input ( " Enter your age : " )
3 age = int ( age_str )
# Explicitly convert the string to an integer
1
2
4
5
6
# Using an f - string for easy formatting
print ( f " Hello , { name }! You are { age } years old . " )
2.4
Operators
Key Information
Most operators are the same, but logical and some arithmetic operators differ.
3
Operation
C++
Operator
Python
Operator
Notes
Logical AND
&&
and
Logical OR
||
or
Logical NOT
!
not
Integer Division
/
//
In C++, 7 / 2 is 3.
In Python, 7 // 2 is
3.
Float Division
/
/
In Python, 7 / 2 is
3.5.
Exponentiation
pow(x, y)
x ** y
Control Structures
Python uses colons : and indentation to manage control flow, whereas C++ uses braces
{} and parentheses ().
3.1
Conditional Statements
Python’s else if is shortened to elif.
3.1.1 C++ Approach
int score = 85;
if ( score >= 90) {
3
std :: cout << " Grade : A " ;
1
2
A Developer’s Translation Guide
C++ to Python Guide
6
} else if ( score >= 80) {
std :: cout << " Grade : B " ;
6 } else {
7
std :: cout << " Grade : C or lower " ;
8 }
4
5
3.1.2 Python Equivalent
score = 85
if score >= 90:
3
print ( " Grade : A " )
4 elif score >= 80:
5
print ( " Grade : B " )
6 else :
7
print ( " Grade : C or lower " )
1
2
3.2
For Loops
The C++ for loop is counter-based. The Python for loop is a ”for-each” loop that
iterates over a sequence. To achieve the C++ behavior, you use the range() function.
3.2.1 C++ Approach (Counter-based)
for ( int i = 0; i < 5; i ++) {
std :: cout << i << " " ;
3 }
4 // Output : 0 1 2 3 4
1
2
3.2.2 Python Equivalent (Using range)
# range ( stop ) -> from 0 up to ( but not including ) stop
for i in range (5) :
3
print (i , end = " " )
4 # Output : 0 1 2 3 4
1
2
5
# range ( start , stop )
for i in range (1 , 6) :
8
print (i , end = " " )
9 # Output : 1 2 3 4 5
6
7
10
# range ( start , stop , step )
for i in range (10 , 0 , -2) :
13
print (i , end = " " )
14 # Output : 10 8 6 4 2
11
12
3.3
While Loops
The structure is very similar, differing mainly in syntax (parentheses vs. colons/indentation).
A Developer’s Translation Guide
C++ to Python Guide
7
3.3.1 C++ Approach
int i = 0;
while ( i < 5) {
3
std :: cout << i << " " ;
4
i ++;
5 }
1
2
3.3.2 Python Equivalent
i = 0
while i < 5:
3
print (i , end = " " )
4
i += 1
1
2
3.4
Absence of do-while and switch
do-while: Python does not have a direct equivalent of the C++ do-while loop.
The common pattern to ensure a block runs at least once is to use an infinite loop
with a conditional break.
while True :
user_input = input ( " Enter ’ quit ’ to exit : " )
3
if user_input == " quit " :
4
break
1
2
switch: Python does not have a switch statement. This logic is typically handled
with a series of if-elif-else statements or by using a dictionary to map cases to
functions.
4
Functions and Recursion
Functions are the primary way to structure code in both languages. However, their
definition and behavior with parameters differ significantly.
4.1
Function Definition and Return Values
In C++, a function must have a declared return type. In Python, functions are defined
with the def keyword and have no declared return type. A Python function that does
not explicitly return a value implicitly returns None.
4.1.1 C++ Approach
1
2
# include < iostream >
# include < string > // For std :: string
3
4
5
// A function that returns a value
int add ( int a , int b ) {
A Developer’s Translation Guide
C++ to Python Guide
return a + b ;
6
7
8
}
8
// A " procedure " that does not return a value
void print_message ( std :: string msg ) {
11
std :: cout << msg << std :: endl ;
12 }
9
10
4.1.2 Python Equivalent
Python makes no distinction between a ”function” and a ”procedure”. A function can
also easily return multiple values, which are automatically packed into a data type called
a tuple.
# A function that returns a single value
def add (a , b ) :
3
return a + b
1
2
4
# A function that performs an action and returns None implicitly
def print_message ( msg ) :
7
print ( msg )
5
6
8
# A function that returns multiple values
def get_point () :
11
x = 10
12
y = 20
13
return x , y # Returns a tuple : (10 , 20)
9
10
14
# You can " unpack " the returned tuple into multiple variables
px , py = get_point ()
17 print ( f " Got point : x ={ px } , y ={ py } " )
15
16
4.2
Parameter Passing
This is a critical difference. C++ has explicit pass-by-value and pass-by-reference.
Python uses a mechanism called ”pass-by-assignment” or ”pass-by-object-reference”.
The practical effect in Python is:
Immutable types (like int, float, str, bool, tuple) behave as if they are passed
by value. The original variable cannot be changed by the function.
Mutable types (like list, dict) behave as if they are passed by reference. The
function can modify the original object.
4.2.1 C++ Example (By Value vs. By Reference)
1
# include < vector >
2
void modify_value ( int val ) { // Pass - by - value
val = 100;
5 }
3
4
6
7
void modify_list ( std :: vector < int > & vec ) { // Pass - by - reference
A Developer’s Translation Guide
C++ to Python Guide
vec . push_back (100) ;
8
9
9
}
4.2.2 Python Equivalent
# For immutable types ( e . g . , int ) , it acts like pass - by - value
def modify_value ( val ) :
3
val = 100
4
# ’ val ’ inside the function now refers to a new integer object
1
2
5
# For mutable types ( e . g . , list ) , it acts like pass - by - reference
def modify_list ( a_list ) :
8
a_list . append (100)
9
# The function modifies the original list object it received
6
7
10
# --- Demonstration --my_num = 10
13 modify_value ( my_num )
14 print ( my_num )
# Output : 10 ( The original is unchanged )
11
12
15
my_list = [1 , 2]
modify_list ( my_list )
18 print ( my_list ) # Output : [1 , 2 , 100] ( The original is modified )
16
17
4.3
Recursion
The logical concept of recursion is identical in both languages. The implementation in
Python is often syntactically cleaner due to its dynamic typing and simpler function
definition.
4.3.1 C++ Recursive Factorial
long long factorial ( int n ) {
if ( n == 0 || n == 1) { // Base case
3
return 1;
4
} else { // Recursive step
5
return n * factorial ( n - 1) ;
6
}
7 }
1
2
4.3.2 Python Recursive Factorial
def factorial ( n ) :
if n == 0 or n == 1: # Base case
3
return 1
4
else : # Recursive step
5
return n * factorial ( n - 1)
1
2
A Developer’s Translation Guide
C++ to Python Guide
5
10
Introduction to Python’s Core Data Structures
Python’s built-in data structures are high-level and flexible, serving as powerful replacements for C++’s lower-level static structures. This section introduces the direct mappings. Part 3 will provide a deeper dive into their usage.
5.1
From Static Arrays to the Python list
In C++, an array is a low-level, fixed-size block of memory. In Python, the list is
the primary replacement, offering a high-level, dynamic, and versatile object for ordered
collections.
5.1.1 C++ Array
1
2
int grades [5]; // Declares a fixed - size array for 5 integers
grades [0] = 88;
5.1.2 Python list Equivalent
# A list can be created with initial values or empty
grades = [88 , 92 , 75]
3 print ( grades [0]) # Access is the same : 88
1
2
4
# Lists are dynamic and can be grown
grades . append (65)
7 print ( grades ) # Output : [88 , 92 , 75 , 65]
5
6
5.2
From std::string to the Python str
Python’s string handling is a core feature. The main philosophical difference is that
Python strings are immutable.
5.2.1 C++ std::string
1
2
std :: string greeting = " Hello " ;
greeting += " , World ! " ; // Modifies the string in place
5.2.2 Python str Equivalent
greeting = " Hello "
# greeting [0] = ’J ’ # This would cause a TypeError
3 greeting = greeting + " , World ! " # This creates a new string object
4 print ( greeting )
1
2
A Developer’s Translation Guide
C++ to Python Guide
5.3
11
From struct to the Python dict
For simple data aggregation, the C++ struct maps almost directly to a Python dictionary (dict), which is a collection of key-value pairs.
5.3.1 C++ struct
struct Student {
int id ;
3
std :: string name ;
4 };
1
2
5
Student s1 ;
s1 . id = 101;
8 s1 . name = " Noureddine " ;
6
7
5.3.2 Python dict Equivalent
# A dictionary is created with curly braces {}
student_1 = {
3
" id " : 101 ,
4
" name " : " Noureddine "
5 }
1
2
6
7
8
# Access members using square brackets and the key ( as a string )
print ( f " Student Name : { student_1 [ ’ name ’]} " ) # Output : Noureddine
9
# Adding a new field is trivial
student_1 [ ’ major ’] = " Artificial Intelligence "
12 print ( student_1 )
13 # Output : { ’ id ’: 101 , ’ name ’: ’ Noureddine ’, ’ major ’: ’ AI ’}
10
11
6
Deep Dive: The Python list and dict
While Part 2 introduced the Python list and dict as replacements for C++ arrays and
structs, this section explores their rich functionality in more detail. Mastering these two
types is essential for writing effective Python code.
6.1
The Python list: More Than an Array
A Python list is a mutable, ordered sequence of objects. Unlike a C++ array, it is not
a raw block of memory but a high-level object with extensive built-in capabilities.
6.1.1 List Creation
Beyond simple initialization, lists can be created dynamically. A particularly powerful
Python-native feature is the list comprehension.
1
2
# Simple creation
numbers = [1 , 2 , 3 , 4 , 5]
3
A Developer’s Translation Guide
C++ to Python Guide
12
# Create a list of 10 zeros , similar to C ++ ‘ int arr [10] = {0}; ‘
zeros = [0] * 10
6 print ( zeros ) # Output : [0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0]
4
5
7
# List comprehension : create a new list based on an existing sequence
# C ++ equivalent would require a for loop and push_back
10 squares = [ x * x for x in range (1 , 6) ]
11 print ( squares ) # Output : [1 , 4 , 9 , 16 , 25]
8
9
12
# Filtering with a list comprehension
even_squares = [ x * x for x in range (1 , 11) if x % 2 == 0]
15 print ( even_squares ) # Output : [4 , 16 , 36 , 64 , 100]
13
14
6.1.2 Advanced Indexing: Negative Indexing and Slicing
Python’s indexing is more flexible than C++’s.
Negative Indexing: You can access elements from the end of the list. -1 is the
last element, -2 is the second to last, and so on.
Slicing: You can extract sub-lists using the syntax list[start:stop:step]. This
is extremely powerful and replaces many manual C++ loops. The stop index is
non-inclusive.
1
letters = [ ’a ’ , ’b ’ , ’c ’ , ’d ’ , ’e ’ , ’f ’]
2
# Negative Indexing
print ( letters [ -1]) # Output : f
5 print ( letters [ -2]) # Output : e
3
4
6
# Slicing
first_three = letters [0:3] # or just letters [:3]
9 print ( first_three ) # Output : [ ’ a ’, ’b ’, ’c ’]
7
8
10
11
12
middle_part = letters [2:5]
print ( middle_part ) # Output : [ ’ c ’, ’d ’, ’e ’]
13
14
15
f r o m _ i n d e x _ 3 _ o n w a r d s = letters [3:]
print ( f r o m _ i n d e x _ 3 _ o n w a r d s ) # Output : [ ’ d ’, ’e ’, ’f ’]
16
# Slicing with a step
ev e r y _o t h er _ e le m e nt = letters [::2]
19 print ( e ve r y _o t h er _ e le m e nt ) # Output : [ ’ a ’, ’c ’, ’e ’]
17
18
20
# Reverse a list with slicing
reversed_list = letters [:: -1]
23 print ( reversed_list ) # Output : [ ’ f ’, ’e ’, ’d ’, ’c ’, ’b ’, ’a ’]
21
22
6.1.3 Common list Methods
The following methods are part of the list object and provide common functionality
that would require helper functions in C++.
list.append(item): Adds an item to the end of the list.
A Developer’s Translation Guide
C++ to Python Guide
13
list.insert(index, item): Inserts an item at a specific index.
list.pop(index=-1): Removes and returns the item at the given index. If no
index is specified, it removes and returns the last item (making the list behave like
a stack).
list.remove(value): Removes the first occurrence of a specific value. Raises a
ValueError if the value is not found.
list.sort(): Sorts the list in-place.
list.reverse(): Reverses the list in-place.
list.count(value): Returns the number of times a value appears in the list.
list.index(value): Returns the index of the first occurrence of a value.
6.1.4 Iteration Techniques
Python’s for loop is designed to iterate over sequences like lists directly.
1
data = [10 , 20 , 30]
2
# Standard iteration ( over values )
for item in data :
5
print ( item , end = " " ) # Output : 10 20 30
6 print ()
3
4
7
# Iterating with index using enumerate ()
for index , item in enumerate ( data ) :
10
print ( f " Index : { index } , Value : { item } " )
8
9
11
# Checking for existence with the ’ in ’ keyword
# C ++ requires a loop to search . Python is much cleaner .
14 if 20 in data :
15
print ( " Found 20 in the list ! " )
12
13
6.2
The Python dict: A Powerful Mapping Tool
A Python dictionary (dict) is an unordered (in older Python versions) or insertionordered (Python 3.7+) collection of key-value pairs. It is the core mapping type in the
language.
6.2.1 Safe Access and Iteration
While you can access values with dict[’key’], this will raise a KeyError if the key
doesn’t exist. The .get() method is a safer alternative. Iteration over dictionaries has
several common patterns.
1
student = { " id " : 101 , " name " : " Noureddine " }
2
# Safe access with . get ()
# . get ( key , d e f a u l t _ v a l u e _ i f _ n o t _ f o u n d )
5 major = student . get ( ’ major ’ , ’ Undeclared ’)
3
4
A Developer’s Translation Guide
C++ to Python Guide
6
14
print ( f " Major : { major } " ) # Output : Major : Undeclared
7
8
# --- Iteration Patterns ---
9
# 1. Iterating over keys ( this is the default behavior )
print ( " Keys : " )
12 for key in student :
13
print ( key )
10
11
14
# 2. Iterating over values
print ( " Values : " )
17 for value in student . values () :
18
print ( value )
15
16
19
# 3. Iterating over key - value pairs ( most common )
print ( " Items : " )
22 for key , value in student . items () :
23
print ( f " { key }: { value } " )
20
21
6.2.2 Dictionary as a switch Statement Replacement
Since Python has no switch statement, a dictionary can be used to map cases to outcomes
or functions, providing a clean and extensible alternative.
1
2
def case_add (a , b ) :
return a + b
3
4
5
def case_subtract (a , b ) :
return a - b
6
7
8
def case_multiply (a , b ) :
return a * b
9
# Dictionary maps operator strings to functions
switch = {
12
’+ ’: case_add ,
13
’ - ’: case_subtract ,
14
’* ’: case_multiply
15 }
10
11
16
17
18
operation = ’+ ’
x , y = 10 , 5
19
# Get the function from the dictionary and call it
# . get () provides a default " case " if the key isn ’t found
22 action = switch . get ( operation , lambda a , b : print ( " Invalid operation " ) )
23 result = action (x , y )
24 print ( f " Result of { x } { operation } { y } is { result } " ) # Output : 15
20
21
7
The Object-Oriented Paradigm in Python
In C++, Object-Oriented Programming (OOP) is a paradigm you consciously adopt,
using keywords like class and access specifiers. In Python, almost everything is an
A Developer’s Translation Guide
C++ to Python Guide
15
object, so OOP is more deeply integrated. This section maps the fundamental C++
class definition to its Python equivalent.
7.1
Defining a Class
The C++ class keyword is also used in Python, but the structure is different. Python
classes do not have separate declaration and implementation files (.h/.cpp) by default;
the entire class is typically defined in a single block.
7.1.1 The Constructor:
init
In C++, the constructor has the same name as the class. In Python, the constructor is a
special method named init . This method is called automatically when a new object
is created.
7.1.2 The self Parameter (Python’s this)
In C++, the this pointer is an implicit keyword that refers to the current object. In
Python, a reference to the current object must be passed explicitly as the first parameter
to every instance method. By strong convention, this parameter is always named self.
7.1.3 Attributes and Methods
C++ requires data members to be declared within the class body. Python attributes are
typically created within the init method by assigning them to self.
7.1.4 C++ Class Structure
class Temperature {
private :
3
double kelvin ; // Private data member
1
2
4
public :
// Constructor
7
Temperature ( double k ) {
8
kelvin = k ;
9
}
5
6
10
// Member function ( method )
void setCelsius ( double c ) {
kelvin = c + 273.15;
}
11
12
13
14
15
// Const member function
double getKelvin () const {
return kelvin ;
}
16
17
18
19
20
};
A Developer’s Translation Guide
C++ to Python Guide
16
7.1.5 Python Class Equivalent
class Temperature :
# The __init__ method is the constructor .
3
# ’ self ’ is the first parameter , referring to the instance .
4
def __init__ ( self , k ) :
5
# Attributes are created by assigning to ’ self ’.
6
# By convention , a single underscore denotes a " protected "
member .
7
self . _kelvin = k
1
2
8
# A " method " ( member function ) . ’ self ’ must be the first parameter .
def set_celsius ( self , c ) :
self . _kelvin = c + 273.15
9
10
11
12
# A method to get a value . There is no ’ const ’ keyword .
def get_kelvin ( self ) :
return self . _kelvin
13
14
15
16
# Creating an instance ( object )
t1 = Temperature (298.15) # __init__ is called automatically
19 t1 . set_celsius (25)
20 print ( t1 . get_kelvin () )
17
18
7.2
The Destructor:
del
C++ has a deterministic destructor, ~ClassName(), which is called automatically when
an object goes out of scope. Python has a counterpart, del , but its behavior is very
different and less reliable.
C++ Destructor: Guaranteed to run the moment the object’s lifetime ends. This
makes it ideal for resource management (RAII).
Python del : Called by the garbage collector at some point after the object is
no longer referenced. There is no guarantee about *when* it will be called, or
even *if* it will be called at all before the program exits.
Conclusion: You should not use del for critical resource management (like closing
files or network connections) in the way you would use a C++ destructor. Python’s with
statement is the correct tool for that, which will be covered in Part 8.
class ResourceWrapper :
def __init__ ( self , name ) :
3
self . name = name
4
print ( f " Resource ’{ self . name } ’ acquired . " )
1
2
5
6
7
8
def __del__ ( self ) :
# This is for demonstration . Do not use for critical cleanup !
print ( f " Resource ’{ self . name } ’ being garbage collected ( __del__
called ) . " )
9
def create_resource () :
print ( " Entering function . " )
12
r = ResourceWrapper ( " MyResource " )
10
11
A Developer’s Translation Guide
C++ to Python Guide
17
print ( " Leaving function . " )
# ’r ’ goes out of reference here . __del__ will be called later .
13
14
15
16
17
create_resource ()
print ( " Function has finished . Garbage collection may happen now or
later . " )
7.3
Access Control: Public, Protected, and Private
This is another major philosophical difference. C++ enforces access control at the compiler level. Python operates on convention and trust.
C++ public: Accessible from anywhere.
C++ protected: Accessible by the class and its subclasses.
C++ private: Accessible only by the class itself.
In Python, there are no such keywords. Access control is managed by naming conventions.
member: Anything without a leading underscore is considered public and part of
the official interface of the class.
member: A single leading underscore signifies a protected member. It is a convention that tells other programmers, ”This is for internal use or for subclasses, please
don’t touch it from the outside.” There is no actual technical prevention.
member: A double leading underscore triggers Python’s name mangling. This
is the closest Python gets to private. The interpreter changes the name of the
attribute to ClassName member, making it difficult (but not impossible) to access
from outside the class.
7.3.1 Python Access Control Example
class MyClass :
def __init__ ( self ) :
3
self . public_var = " I am public "
4
self . _protected_var = " I am for internal / subclass use "
5
self . __private_var = " I am ’ private ’"
1
2
6
7
8
9
10
def print_vars ( self ) :
print ( self . public_var )
print ( self . _protected_var )
print ( self . __private_var ) # Accessible inside the class
11
12
obj = MyClass ()
13
14
15
# Public access is fine
print ( obj . public_var )
16
17
18
# Protected access is technically possible , but bad practice
print ( obj . _protected_var )
A Developer’s Translation Guide
C++ to Python Guide
18
19
20
21
# Private access fails with the normal name
# print ( obj . __private_var ) # This would raise an AttributeError
22
23
24
# ... but it can still be accessed if you know the mangled name
print ( obj . _ M y C l a s s _ _ p r i v a t e _ v a r ) # This works , but you should never do
it .
8
Advanced Class Features and Structure
Beyond the basic class definition, C++ offers features like const correctness, static
members, and friend access. Python achieves similar goals through different mechanisms, often relying on conventions and its dynamic nature.
8.1
The Philosophy of const in Python
C++ uses the const keyword to enforce read-only access for objects and to declare that
a member function will not modify the object’s state. Python has no const keyword and
operates on a different philosophy.
No Compiler Enforcement: Python does not prevent you from modifying an
object. The design philosophy is often summarized as ”we’re all consenting adults
here,” meaning the programmer is trusted not to modify things that shouldn’t be
changed.
Conceptual Equivalence: A Python method that does not modify any attributes
of self is conceptually equivalent to a C++ const member function.
Read-Only Properties: To create attributes that are read-only from the outside,
the @property decorator is the Pythonic way. This creates a ”getter” that can be
accessed like an attribute, without an obvious ”setter”.
8.1.1 C++ const Example
class Config {
private :
3
const int id ;
4
std :: string name ;
5 public :
6
Config ( int i , std :: string n ) : id ( i ) , name ( n ) {}
1
2
7
int getID () const { // Const method , can be called on const objects
return id ;
}
std :: string getName () const {
return name ;
}
8
9
10
11
12
13
14
};
A Developer’s Translation Guide
C++ to Python Guide
19
8.1.2 Python Equivalent using @property
Key Information
The @property decorator turns a method into a read-only attribute.
Python Code
class Config :
def __init__ ( self , config_id , name ) :
3
# By convention , _id is " private " and should not be changed
4
self . _id = config_id
5
self . _name = name
1
2
6
@property
def config_id ( self ) :
# This makes ’ config_id ’ a read - only property
return self . _id
7
8
9
10
11
@property
def name ( self ) :
return self . _name
12
13
14
15
16
17
# --- Usage --conf = Config (101 , " System . Default " )
18
# Access the properties like attributes
print ( f " ID : { conf . config_id } " )
# Calls the config_id () method
21 print ( f " Name : { conf . name } " )
# Calls the name () method
19
20
22
23
24
# Attempting to write to the property will fail
# conf . config_id = 202 # This would raise an AttributeError
8.2
Composition (“Has-A” Relationships)
Key Information
The concept of building complex objects by including other objects as members is
identical in both languages. The syntax in Python is often more direct.
A Developer’s Translation Guide
C++ to Python Guide
20
8.2.1 C++ Composition Example
C++ Code
1
class Address { /* ... */ };
2
class Employee {
private :
5
std :: string name ;
6
Address homeAddress ; // Member object
7 public :
8
// Constructor initializes member object in initializer list
Employee ( std :: string n , Address addr ) : name ( n ) , homeAddress ( addr
) {}
9 };
3
4
8.2.2 Python Composition Equivalent
Key Information
In Python, you simply create an instance of the contained class and assign it to an
attribute of the container class.
Python Code
class Address :
def __init__ ( self , street , city ) :
3
self . street = street
4
self . city = city
1
2
5
class Employee :
def __init__ ( self , name , address_obj ) :
8
self . name = name
9
# The Employee object " has - an " Address object
10
self . home_address = address_obj
6
7
11
# --- Usage --addr = Address ( " 123 Main St " , " Anytown " )
14 emp = Employee ( " Bob " , addr )
12
13
15
16
17
# Access the composed object ’s attributes
print ( f " { emp . name } lives at { emp . home_address . street } " )
8.3
static Members and Methods
Key Information
In C++, static members belong to the class rather than an instance. Python has
direct equivalents for this feature.
A Developer’s Translation Guide
C++ to Python Guide
21
• C++ static data member: A single variable shared among all instances of the
class. It must be defined outside the class.
• Python Class Attribute: A variable defined directly in the class scope (not inside
init ) is shared among all instances.
• C++ static member function: A function that belongs to the class but does
not have a this pointer. It can be called using the class name.
• Python @staticmethod: A decorator that defines a static method. It does not
receive the implicit first argument (self). It is essentially a namespaced function
within the class.
• Python @classmethod: A Python-specific feature. A class method receives the
class itself as the first argument, conventionally named cls. This is useful for
factory methods that need to work with the class, for instance, to call other class
methods or its constructor.
8.3.1 C++ static Example
C++ Code
class Thing {
private :
3
static int count ; // Declaration
4 public :
5
Thing () { count ++; }
6
static int getCount () { return count ; } // Static method
7 };
8 // Definition outside the class
9 int Thing :: count = 0;
1
2
A Developer’s Translation Guide
C++ to Python Guide
22
8.3.2 Python static and class Method Equivalents
Python Code
class Thing :
# This is a class attribute , equivalent to a C ++ static data
member
3
count = 0
1
2
4
def __init__ ( self ) :
# To modify the class attribute , refer to it via the class
name
Thing . count += 1
5
6
7
8
@staticmethod
def get_count () :
# A static method does not get ’ self ’ or the class
# It can access class attributes through the class name
return Thing . count
9
10
11
12
13
14
@classmethod
def f ro m _ st r i ng _ f ac t o ry ( cls , data_string ) :
# A class method gets the class ( ’ cls ’) as its first argument
# It can be used to create instances of the class
print ( f " Factory in class { cls . __name__ } was called . " )
# ... logic to parse data_string ...
return cls () # Returns a new instance of Thing
15
16
17
18
19
20
21
22
# --- Usage --print ( f " Initial count : { Thing . get_count () } " ) # Call static method
25 t1 = Thing ()
26 t2 = Thing ()
27 print ( f " Final count : { t1 . count } " ) # Can be accessed via instance or
class
28 print ( f " Final count : { Thing . count } " )
23
24
29
30
31
# Using the class method factory
t3 = Thing . f ro m _ st r i ng _ f ac t o ry ( " some_data " )
8.4
The friend Concept
Important Note
C++ uses the friend keyword to grant an external function or class special access
to its private and protected members, effectively bypassing encapsulation.
• Python has no friend keyword. The concept is not needed because Python’s
access control is based on convention. As seen before, there is no strict enforcement
of privacy. A programmer can always access protected members, and can even
access private members by using the mangled name. Python’s philosophy trusts
the developer not to misuse internal state, rendering friend unnecessary.
A Developer’s Translation Guide
C++ to Python Guide
8.5
23
Modules: Python’s Answer to .h/.cpp Files
Key Information
In C++, it is standard practice to separate a class’s interface (declaration) into a
header file (.h) and its implementation into a source file (.cpp). This separates the
”what” from the ”how” and helps manage compilation dependencies.
Python does not use this model. Instead, it uses modules.
• A module is simply a Python file (.py).
• A class, its methods, and any related functions are typically defined in the same
.py file.
• To use a class from another file, you import the module.
8.5.1 C++ File Separation
// file: MyUtility.h
class MyUtility {
public:
void performAction();
};
// file: MyUtility.cpp
#include "MyUtility.h"
#include <iostream>
void MyUtility::performAction() {
std::cout << "Action performed." << std::endl;
}
// file: main.cpp
#include "MyUtility.h"
int main() {
MyUtility util;
util.performAction();
}
A Developer’s Translation Guide
C++ to Python Guide
24
8.5.2 Python Module Equivalent
Python Code
# file : my_utility . py
class MyUtility :
3
" " " A utility class defined in the my_utility module . " " "
4
def perform_action ( self ) :
5
print ( " Action performed . " )
1
2
6
def helper_function () :
" " " A helper function in the same module . " " "
9
print ( " Helper function called . " )
7
8
10
# file : main . py
# Import the specific class from the my_utility module
13 from my_utility import MyUtility
11
12
14
# You can also import the entire module :
# import my_utility
17 # and then use my_utility . MyUtility ()
15
16
18
def main () :
util = MyUtility ()
21
util . perform_action ()
19
20
22
23
24
if __name__ == " __main__ " :
main ()
8.6
A Note on Design Patterns: The Proxy Class
Key Information
Design patterns are conceptual solutions to common software problems. The Proxy
pattern, which involves a class acting as an interface to another object, translates
directly to Python. The implementation is often simpler due to Python’s dynamic
nature.
8.6.1 C++ Proxy Concept
A Proxy class holds a pointer to a ”Real Subject” object and controls access to it,
forwarding method calls. This hides the Real Subject’s implementation from the client.
A Developer’s Translation Guide
C++ to Python Guide
25
8.6.2 Python Proxy Equivalent
Python Code
class HeavyResource :
" " " The real object that is expensive to create or use . " " "
3
def perform_action ( self ) :
4
print ( " HeavyResource is performing a major action . " )
1
2
5
class ResourceProxy :
" " " The proxy class that controls access to HeavyResource . " " "
8
def __init__ ( self ) :
9
# Using lazy initialization : the heavy object is not created
10
# until it is actually needed .
11
self . _resource = None
6
7
12
def perform_action ( self ) :
# The proxy can add its own logic , like logging or access
checks .
print ( " Proxy : Logging access before action . " )
13
14
15
16
if self . _resource is None :
print ( " Proxy : Creating HeavyResource now ( lazy init ) . " )
self . _resource = HeavyResource ()
17
18
19
20
# Forward the call to the real object
self . _resource . perform_action ()
21
22
23
# --- Usage --# The client only ever interacts with the proxy .
26 proxy = ResourceProxy ()
24
25
27
28
29
# The heavy resource is not created yet .
print ( " Proxy created . " )
30
31
32
# The first call to perform_action will trigger creation .
proxy . perform_action ()
33
34
35
# The second call uses the already - created object .
proxy . perform_action ()
9
Inheritance and Polymorphism
Key Information
Inheritance and polymorphism are pillars of OOP that allow for code reuse and flexible, extensible designs. Python supports both concepts, but with a more dynamic
and less syntactically rigid approach than C++.
A Developer’s Translation Guide
C++ to Python Guide
9.1
26
Inheritance
Inheritance allows a ”derived” or ”child” class to inherit attributes and methods
from a ”base” or ”parent” class. This models an ”is-a” relationship (e.g., a Car is
a Vehicle).
9.1.1 Inheritance Syntax
Key Information
In C++, you specify the inheritance type (public, protected, private). In Python,
inheritance is always public in its effect, and the syntax is simpler.
C++ Code
1
2
// Base class
class Device { /* ... */ };
3
4
5
// Derived class
class Thermostat : public Device { /* ... */ };
Python Code
# Base class
class Device :
3
# ...
4
pass # ’ pass ’ is a placeholder for an empty block
1
2
5
# Derived class syntax : class ChildClassName ( ParentClassName ) :
class Thermostat ( Device ) :
8
# ...
9
pass
6
7
9.1.2 Calling the Base Class Constructor
Key Information
A derived class constructor must call its base class’s constructor to ensure the base
part of the object is properly initialized. C++ uses the member initializer list for
this. Python uses the built-in super() function.
A Developer’s Translation Guide
C++ to Python Guide
27
C++ Code
class Device {
public :
3
Device ( std :: string id ) : deviceID ( id ) {}
4 private :
5
std :: string deviceID ;
6 };
1
2
7
class Thermostat : public Device {
public :
10
// Calling the base constructor in the initializer list
11
Thermostat ( std :: string id , double temp ) : Device ( id ) {
12
// ... thermostat - specific initialization ...
13
}
14 };
8
9
Python Code
class Device :
def __init__ ( self , device_id ) :
3
self . device_id = device_id
1
2
4
class Thermostat ( Device ) :
def __init__ ( self , device_id , temp ) :
7
# super () gets a reference to the parent class .
8
# Call its __init__ method to initialize the Device part .
9
super () . __init__ ( device_id )
5
6
10
11
12
# Thermostat - specific initialization
self . temperature = temp
13
# --- Usage --thermo = Thermostat ( " thermo -01 " , 21.5)
16 print ( thermo . device_id )
# ’ device_id ’ was inherited from Device
17 print ( thermo . temperature )
# ’ temperature ’ is specific to Thermostat
14
15
9.1.3 Method Overriding and Accessing Base Methods
To override a base class method, you simply define a method with the same name in the
derived class. To call the base class’s version of that method from the overridden method,
you again use super().
class Parent :
def speak ( self ) :
3
print ( " Parent speaking . " )
1
2
4
class Child ( Parent ) :
def speak ( self ) :
7
# First , call the parent ’s version of the method
8
super () . speak ()
9
# Then , add the child ’s specific behavior
10
print ( " Child speaking . " )
5
6
A Developer’s Translation Guide
C++ to Python Guide
28
11
c = Child ()
c . speak ()
14 # Output :
15 # Parent speaking .
16 # Child speaking .
12
13
9.2
Polymorphism
Polymorphism allows objects of different derived classes to be treated through a common
base class interface.
9.2.1 The virtual Keyword is Implicit
This is a fundamental difference. In C++, for a method call on a base class pointer
to be resolved at runtime (dynamic binding), the base class method must be declared
virtual.
In Python, all methods are virtual by default. There is no virtual keyword
because there is no static binding in this context. When you call a method on an object,
Python always looks up the correct method to call at runtime based on the object’s actual
type.
9.2.2 Polymorphism Example
// C ++ requires ’ virtual ’ for this to work polymorphically
class Document {
3 public :
4
virtual void print () { /* generic print */ }
5 };
6 class Pdf : public Document {
7 public :
8
void print () override { /* pdf - specific print */ }
9 };
10 class Word : public Document {
11 public :
12
void print () override { /* word - specific print */ }
13 };
1
2
14
// C ++ polymorphic usage
std :: vector < Document * > docs = { new Pdf () , new Word () };
17 for ( Document * doc : docs ) {
18
doc - > print () ; // Calls the correct derived version
19 }
15
16
class Document :
def print_doc ( self ) :
3
print ( " Printing a generic document . " )
1
2
4
class Pdf ( Document ) :
def print_doc ( self ) :
7
print ( " Printing a PDF document with high resolution . " )
5
6
8
9
class Word ( Document ) :
A Developer’s Translation Guide
C++ to Python Guide
29
def print_doc ( self ) :
print ( " Printing a Word document with spell check . " )
10
11
12
13
14
# Python polymorphic usage is natural
documents = [ Pdf () , Word () , Document () ]
15
for doc in documents :
# Python automatically calls the correct ’ print_doc ’ method
18
# based on the object ’s actual type at runtime .
19
doc . print_doc ()
16
17
9.2.3 Absence of the final Keyword
C++11 introduced the final specifier to prevent a class from being inherited or a method
from being overridden. Python does not have a final keyword, reflecting its more open
and dynamic philosophy. While advanced techniques using metaclasses can simulate this,
it is not a standard feature of the language.
9.3
Abstract Base Classes (ABCs)
In C++, an abstract class is created by including at least one pure virtual function
(= 0;). This prevents the class from being instantiated and forces derived classes to
implement that function. Python achieves this through its standard abc (Abstract Base
Class) module.
9.3.1 C++ Abstract Class
class Shape { // Abstract because of the pure virtual function
public :
3
virtual double area () const = 0; // Pure virtual function
4 };
1
2
9.3.2 Python ABC Equivalent
1
import abc
2
3
4
# Inherit from abc . ABC to mark this as an abstract base class
class Shape ( abc . ABC ) :
5
6
7
8
9
@abc . abstractmethod
def area ( self ) :
" " " This method must be implemented by concrete subclasses . " " "
pass
10
class Square ( Shape ) :
def __init__ ( self , side ) :
13
self . side = side
11
12
14
15
16
17
# Square must implement the ’ area ’ method
def area ( self ) :
return self . side * self . side
18
A Developer’s Translation Guide
C++ to Python Guide
30
# --- Usage --# s = Shape () # This would raise a TypeError : Can ’t instantiate
abstract class
21 sq = Square (5)
22 print ( f " Area of square is : { sq . area () } " )
19
20
9.4
Runtime Type Information (RTTI)
In C++, you use dynamic cast to safely check if a base pointer actually points to a
derived object, and typeid to inspect the exact type. Python, being dynamic, has
simpler, built-in tools for this.
dynamic cast is best mapped to Python’s isinstance().
typeid is best mapped to Python’s type().
In general, isinstance() is preferred for polymorphic code, as it correctly identifies
objects of derived classes, respecting the ”is-a” relationship.
9.4.1 C++ RTTI Example
void process ( Shape * s ) {
// Check if s is actually a Square before calling a Square - only
method
3
if ( Square * sq = dynamic_cast < Square * >( s ) ) {
4
// sq - > s qu ar e_ on ly _m et ho d () ;
5
}
6 }
1
2
9.4.2 Python RTTI Equivalent
class Shape : pass
class Square ( Shape ) :
3
def get_side ( self ) : return 5
4 class Circle ( Shape ) : pass
1
2
5
def process_shape ( s ) :
# isinstance () checks if an object is an instance of a class
8
# OR any subclass of it . This is the preferred Pythonic check .
9
if isinstance (s , Square ) :
10
print ( f " It ’s a Square with side { s . get_side () } " )
11
elif isinstance (s , Circle ) :
12
print ( " It ’s a Circle . " )
13
elif isinstance (s , Shape ) :
14
print ( " It ’s some other Shape . " )
6
7
15
16
17
18
19
# Using type () checks for the EXACT type , ignoring inheritance .
# This is less flexible and usually not what you want .
if type ( s ) is Square :
print ( " The object ’s exact type is Square . " )
20
21
# --- Usage ---
A Developer’s Translation Guide
C++ to Python Guide
22
23
31
process_shape ( Square () )
process_shape ( Circle () )
10
Operator Overloading
Operator overloading allows you to define custom behavior for built-in operators when
used with your class objects. This lets you write more intuitive code, such as adding two
Vector objects with the + symbol. The concept exists in both C++ and Python, but
the syntax is different.
10.1
The Mechanism: From operator@ to Dunder Methods
In C++, you overload operators by defining functions named operator@, where @ is the
symbol (e.g., operator+).
In Python, you implement special methods whose names begin and end with double
underscores. These are often called ”dunder” methods (for Double UNDERscore). For
instance, to overload the + operator, you implement the add method.
The fundamental restrictions are the same in both languages: you cannot change an
operator’s precedence, its arity (the number of operands it takes), or create entirely new
operators.
10.2
Mapping Common Operators
The following table provides a direct translation from the C++ operator function to the
corresponding Python special method.
A Developer’s Translation Guide
C++ to Python Guide
32
Category
Binary Arithmetic
Addition
Subtraction
Multiplication
Division
Integer Division
Modulo
Comparison
Equal to
Not equal to
Less than
Greater than
Less than or equal to
Greater than or equal to
Unary Arithmetic
Negative
Positive
Assignment
Compound Addition
Compound Subtraction
Representation
Stream Insertion
Container Access
Subscript (Read)
Subscript (Write)
10.3
C++ Operator Function
Python Dunder Method
operator+
operatoroperator*
operator/
N/A
operator%
add (self, other)
sub (self, other)
mul (self, other)
truediv (self, other)
floordiv (self, other)
mod (self, other)
operator==
operator!=
operator<
operator>
operator<=
operator>=
eq
ne
lt
gt
le
ge
(self, other)
(self, other)
(self, other)
(self, other)
(self, other)
(self, other)
operatoroperator+
neg (self)
pos (self)
operator+=
operator-=
iadd (self, other)
isub (self, other)
operator<<
str (self) /
operator[]
operator[]
getitem (self, key)
setitem (self, key, value)
Implementation Examples
10.3.1 Binary Operator: Vector Addition
class Vector2D {
public :
3
double x , y ;
4
Vector2D ( double x =0 , double y =0) : x ( x ) , y ( y ) {}
5
Vector2D operator +( const Vector2D & other ) const {
6
return Vector2D ( x + other .x , y + other . y ) ;
7
}
8 };
1
2
class Vector2D :
def __init__ ( self , x =0 , y =0) :
3
self . x = x
4
self . y = y
1
2
5
6
7
8
9
10
11
# Overloads the ’+ ’ operator
def __add__ ( self , other ) :
if isinstance ( other , Vector2D ) :
return Vector2D ( self . x + other .x , self . y + other . y )
# It ’s good practice to handle unsupported types
return NotImplemented
A Developer’s Translation Guide
repr (self)
C++ to Python Guide
33
12
# --- Usage --v1 = Vector2D (2 , 3)
15 v2 = Vector2D (10 , 20)
16 v3 = v1 + v2 # This calls v1 . __add__ ( v2 )
17 print ( f " v3 = ({ v3 . x } , { v3 . y }) " ) # Output : v3 = (12 , 23)
13
14
10.3.2 String Representation:
str
and
repr
C++ uses operator<< to send an object’s representation to a stream like std::cout.
Python has two methods for this:
str (self): Should return a user-friendly, readable string representation of the
object. This is what print() and str() use. This is the closest equivalent to
overloading operator<<.
repr (self): Should return an unambiguous, official string representation of
the object, which, if possible, should be valid Python code to recreate the object
(e.g., Vector2D(10, 20)). This is used for debugging and is the fallback if str
is not defined.
class Vector2D :
def __init__ ( self , x =0 , y =0) :
3
self . x = x
4
self . y = y
1
2
5
6
7
8
def __str__ ( self ) :
# User - friendly output
return f " A 2 D vector at ({ self . x } , { self . y }) "
9
10
11
12
def __repr__ ( self ) :
# Developer - friendly , unambiguous output
return f " Vector2D ( x ={ self . x } , y ={ self . y }) "
13
# --- Usage --v = Vector2D (10 , 20)
16 print ( v ) # Calls __str__ -> Output : A 2 D vector at (10 , 20)
17 print ( repr ( v ) ) # Calls __repr__ -> Output : Vector2D ( x =10 , y =20)
14
15
10.3.3 Subscript Operator:
getitem
and
setitem
In C++, a single operator[] can be used for both reading and writing (by returning a
reference). In Python, these are two distinct methods.
class MyArrayWrapper :
def __init__ ( self ) :
3
# Use a dictionary internally to store data
4
self . _data = {}
1
2
5
6
7
8
9
# For obj [ key ] = value
def __setitem__ ( self , key , value ) :
print ( f " Setting item ’{ key } ’ to ’{ value } ’ " )
self . _data [ key ] = value
A Developer’s Translation Guide
C++ to Python Guide
34
10
11
12
13
14
# For value = obj [ key ]
def __getitem__ ( self , key ) :
print ( f " Getting item ’{ key } ’ " )
return self . _data . get ( key )
15
# --- Usage --my_arr = MyArrayWrapper ()
18 my_arr [ ’ name ’] = " ENSIA "
19 print ( my_arr [ ’ name ’ ])
16
17
10.4
# Calls __setitem__
# Calls __getitem__
Handling Increment/Decrement
Python does not have ++ or -- operators. This is a deliberate design choice to
avoid the ambiguity and subtle bugs they can cause in C++. The Pythonic way is to use
the explicit compound assignment operators += and -=. You can overload these with the
iadd (in-place add) and isub (in-place subtract) methods.
class Counter :
def __init__ ( self , value =0) :
3
self . value = value
1
2
4
5
6
7
8
9
# Overloads the ’+= ’ operator
def __iadd__ ( self , amount ) :
self . value += amount
# In - place methods should return self
return self
10
11
12
def __str__ ( self ) :
return str ( self . value )
13
# --- Usage --c = Counter (10)
16 # c ++ is NOT valid in Python
17 c += 1 # This is the Python way , calling c . __iadd__ (1)
18 print ( c ) # Output : 11
14
15
10.5
Type Conversions
C++ uses conversion constructors and conversion operators. Python handles this through
its dynamic typing and special methods.
C++ Conversion Constructor (MyClass(OtherType)): This is naturally handled by Python’s init , which can accept arguments of any type and perform
logic based on them.
C++ Conversion Operator (operator OtherType()): This maps to specific
dunder methods in Python. To convert your object to an integer, you implement
int (); to a float, float (); to a boolean, bool ().
class Measurement :
def __init__ ( self , value ) :
3
self . value = value
1
2
A Developer’s Translation Guide
C++ to Python Guide
35
4
# Defines how to convert this object to an integer
def __int__ ( self ) :
return int ( self . value )
5
6
7
8
# Defines the object ’s " truthiness "
def __bool__ ( self ) :
return self . value > 0
9
10
11
12
m = Measurement (99.8)
# Now we can use standard type casting functions
15 val_int = int ( m )
16 print ( f " Measurement as int : { val_int } " ) # Output : 99
13
14
17
18
19
if m : # Calls __bool__
print ( " Measurement is considered True . " )
11
Pointers, Memory, and Exceptions
Key Information
This section covers three topics that are handled very differently in Python compared
to C++. C++ gives the programmer low-level control over memory via pointers,
while Python abstracts this away completely. Similarly, Python’s exception handling
syntax is more expressive.
11.1
From Pointers and Manual Memory to References and
Garbage Collection
Important Note
This is the most significant paradigm shift from C++ to Python. In short, Python
does not have pointers, and memory management is automatic.
11.1.1 Absence of Pointers
In C++, a pointer is a variable that stores a memory address. You can directly manipulate
these addresses using operators like & (address-of) and * (dereference).
Python has no pointers. You cannot get the memory address of an object, nor
can you manipulate memory addresses directly.
11.1.2 Object References
Instead of pointers, Python uses object references. Every variable name in Python is a
reference to an object.
▶ When you write x = 100, you are not putting the value 100 into a box called x.
You are creating an integer object with the value 100, and making the name x refer
to it.
A Developer’s Translation Guide
C++ to Python Guide
36
▶ When you write y = x, you are not copying the value. You are creating a second
name, y, that refers to the exact same object that x refers to.
1
2
# x is a name referring to a list object
x = [1 , 2 , 3]
3
4
5
# y is a new name that refers to the SAME list object
y = x
6
7
8
print ( f " x refers to : { x } " ) # Output : [1 , 2 , 3]
print ( f " y refers to : { y } " ) # Output : [1 , 2 , 3]
9
10
11
# Modifying the object through the name ’y ’
y . append (4)
12
# The change is visible through the name ’x ’ because it ’s the same
object
14 print ( f " x now refers to : { x } " ) # Output : [1 , 2 , 3 , 4]
13
11.1.3 Identity vs. Equality: is vs. ==
The concept of two pointers pointing to the same address has a direct parallel in Python.
• a == b: Compares the values of the objects. It calls the
eq
method.
• a is b: Checks if a and b refer to the exact same object in memory. This is
Python’s equivalent of comparing two pointers to see if they hold the same address.
list_a = [1 , 2 , 3]
list_b = [1 , 2 , 3] # A new list object with the same values
3 list_c = list_a
# A new name for the same object as list_a
1
2
4
5
6
print ( list_a == list_b ) # True , because their contents are equal
print ( list_a is list_b ) # False , because they are two different objects
in memory
7
8
9
print ( list_a == list_c ) # True , because their contents are equal
print ( list_a is list_c ) # True , because they refer to the exact same
object
11.1.4 Absence of new and delete
In C++, you use new to allocate memory on the heap and delete to free it.
▶ Python has no new keyword. You create an object simply by calling its constructor: my obj = MyClass(). All user-defined objects are stored on the heap.
▶ Python has no delete keyword for memory. Python’s Garbage Collector
(GC) runs automatically in the background. It keeps track of how many references
point to each object. When an object’s reference count drops to zero, the GC is
free to deallocate its memory. This completely eliminates the category of memory
leak bugs caused by forgetting to call delete.
A Developer’s Translation Guide
C++ to Python Guide
11.2
37
Exception Handling
Python’s exception handling model is very similar to C++’s, but with different keywords
and some additional features.
11.2.1 Mapping try/catch/throw
• C++ throw expression; maps to Python raise ExceptionType("message").
You must ”raise” an instance of an exception class.
• C++ try {...} maps directly to Python try:
....
• C++ catch (Type& e) {...} maps to Python except ExceptionType as e:
11.2.2 C++ Approach
C++ Code
1
# include < stdexcept >
2
double divide ( int num , int den ) {
if ( den == 0) {
5
throw std :: runtime_error ( " Division by zero ! " ) ;
6
}
7
return static_cast < double >( num ) / den ;
8 }
3
4
9
int main () {
try {
12
double result = divide (10 , 0) ;
13
} catch ( const std :: runtime_error & e ) {
14
std :: cerr << " Error caught : " << e . what () << std :: endl ;
15
}
16
return 0;
17 }
10
11
11.2.3 Python Equivalent
def divide ( num , den ) :
if den == 0:
3
# In Python , you raise an instance of an exception
4
raise ValueError ( " Division by zero ! " )
5
return num / den
1
2
6
7
try :
result = divide (10 , 0)
except ValueError as e :
10
# ’e ’ holds the exception object
11
print ( f " Error caught : { e } " )
8
9
A Developer’s Translation Guide
....
C++ to Python Guide
38
11.2.4 The finally and else Clauses
Python’s try...except block has two additional clauses not found in C++.
▶ else: The code in the else block is executed only if the try block completes
without raising an exception.
▶ finally: The code in the finally block is always executed, regardless of whether
an exception occurred or not. It is used for essential cleanup actions.
1
try :
num = int ( input ( " Enter a number : " ) )
result = 100 / num
4 except ValueError :
5
print ( " That was not a valid number . " )
6 except Zer oDivi sionEr ror :
7
print ( " You cannot divide by zero . " )
8 else :
9
# This runs only if NO exceptions were raised
10
print ( f " Success ! The result is { result } " )
11 finally :
12
# This ALWAYS runs , for cleanup .
13
print ( " Execution of the try block is complete . " )
2
3
11.3
RAII and the with Statement
Key Information
RAII (Resource Acquisition Is Initialization) is a core C++ pattern where resource
lifetime is tied to an object’s scope via its constructor and destructor. While Python’s
del is not reliable for this, Python provides a superior and more explicit mechanism for resource management: the with statement.
The with statement works with objects that support the ”context manager” protocol.
Many built-in objects, like files, support this protocol out of the box. It guarantees that
a resource is properly cleaned up, even in the face of exceptions.
11.3.1 C++ File Handling (RAII via Destructor)
C++ Code
# include < fstream >
void process_file () {
3
std :: ofstream file ( " my_file . txt " ) ; // Resource acquired in
constructor
4
file << " Hello " ;
5
// Destructor of ’ file ’ is called at end of scope , closing it .
6
// If an exception occurred before this , the destructor still
runs .
7 }
1
2
A Developer’s Translation Guide
C++ to Python Guide
39
11.3.2 Python Equivalent (The with statement)
def process_file () :
# The ’ with ’ statement acquires the resource ( opens the file )
3
# It guarantees that file . close () will be called automatically
4
with open ( " my_file . txt " , " w " ) as file :
5
file . write ( " Hello " )
6
# No need to manually call file . close ()
1
2
7
8
9
# At this point , after the indented block , the file is guaranteed
# to be closed , even if an error had occurred inside the ’ with ’
block .
10
11
process_file ()
Success Note
The with statement is the idiomatic Python solution for ensuring deterministic
cleanup of resources, serving the same core purpose as RAII in C++.
12
Implementing Dynamic Data Structures
In C++, dynamic data structures like linked lists and trees are built using self-referential
classes and explicit memory management with pointers (new/delete). In Python, the
same logical structures are built using self-referential classes, but Python’s object references and automatic garbage collection replace manual pointer manipulation.
The core logic (e.g., the steps to insert a node) remains the same, but the implementation is cleaner and safer.
12.1
Linked List Implementation
A linked list consists of nodes, where each node contains data and a reference to the next
node.
12.1.1 The Node Class
First, we define the building block. The next attribute is initialized to None, which is
Python’s equivalent of nullptr.
class Node :
" " " A single node in a linked list . " " "
3
def __init__ ( self , data ) :
4
self . data = data
5
self . next = None # Reference to the next node
1
2
12.1.2 The LinkedList Class
This class manages the collection of nodes and provides the main interface for list operations.
A Developer’s Translation Guide
C++ to Python Guide
40
class LinkedList :
def __init__ ( self ) :
3
self . head = None
4
self . tail = None
5
self . count = 0
1
2
# Reference to the first node
# Reference to the last node
6
7
8
def is_empty ( self ) :
return self . head is None
9
10
11
12
def __len__ ( self ) :
# Allows you to call len ( my_list )
return self . count
13
14
15
16
17
def __str__ ( self ) :
# For user - friendly printing
if self . is_empty () :
return " LinkedList : [] "
18
19
20
21
22
23
24
parts = []
current = self . head
while current is not None :
parts . append ( str ( current . data ) )
current = current . next
return f " LinkedList : [{ ’ -> ’. join ( parts ) }] "
25
26
27
28
29
30
31
32
33
34
def insert_at_front ( self , data ) :
new_node = Node ( data )
if self . is_empty () :
self . head = new_node
self . tail = new_node
else :
new_node . next = self . head
self . head = new_node
self . count += 1
35
36
37
38
39
40
41
42
43
44
def insert_at_back ( self , data ) :
new_node = Node ( data )
if self . is_empty () :
self . head = new_node
self . tail = new_node
else :
self . tail . next = new_node
self . tail = new_node
self . count += 1
45
46
47
48
def re move_f rom_fr ont ( self ) :
if self . is_empty () :
raise IndexError ( " Cannot remove from an empty list . " )
49
50
51
data_to_return = self . head . data
node_to_remove = self . head
52
53
54
55
56
57
if self . head is
self . head =
self . tail =
else :
self . head =
self . tail : # Only one node
None
None
self . head . next
A Developer’s Translation Guide
C++ to Python Guide
41
58
59
60
61
# The old node is now unreferenced , garbage collector will
clean it up
self . count -= 1
return data_to_return
62
63
64
65
def remove_from_back ( self ) :
if self . is_empty () :
raise IndexError ( " Cannot remove from an empty list . " )
66
data_to_return = self . tail . data
67
68
if self . head is self . tail : # Only one node
self . head = None
self . tail = None
else :
# Must traverse to find the second - to - last node
current = self . head
while current . next is not self . tail :
current = current . next
69
70
71
72
73
74
75
76
77
self . tail = current
self . tail . next = None
78
79
80
self . count -= 1
return data_to_return
81
82
12.2
Stack Implementation (via Composition)
A stack operates on a Last-In, First-Out (LIFO) principle. It can be easily implemented
by using (composing) a LinkedList and only exposing stack-like methods. This is often
preferred over inheritance in Python for ”is-implemented-using” relationships.
class Stack :
def __init__ ( self ) :
3
self . _list = LinkedList () # Internal LinkedList for storage
1
2
4
5
6
def is_empty ( self ) :
return self . _list . is_empty ()
7
8
9
def __len__ ( self ) :
return len ( self . _list )
10
11
12
13
def push ( self , data ) :
" " " Pushing onto a stack is like inserting at the front of a
list . " " "
self . _list . insert_at_front ( data )
14
15
16
17
def pop ( self ) :
" " " Popping from a stack is like removing from the front of a
list . " " "
return self . _list . re move_f rom_fr ont ()
18
19
20
21
def peek ( self ) :
" " " Peeking at the top element without removing it . " " "
if self . is_empty () :
A Developer’s Translation Guide
C++ to Python Guide
42
raise IndexError ( " Cannot peek at an empty stack . " )
return self . _list . head . data
22
23
12.3
Queue Implementation (via Composition)
A queue operates on a First-In, First-Out (FIFO) principle. This is also easily implemented using our LinkedList.
class Queue :
def __init__ ( self ) :
3
self . _list = LinkedList ()
1
2
4
5
6
def is_empty ( self ) :
return self . _list . is_empty ()
7
8
9
def __len__ ( self ) :
return len ( self . _list )
10
11
12
13
def enqueue ( self , data ) :
" " " Enqueuing is adding to the back of the list . " " "
self . _list . insert_at_back ( data )
14
15
16
17
def dequeue ( self ) :
" " " Dequeuing is removing from the front of the list . " " "
return self . _list . re move_f rom_fr ont ()
18
19
20
21
22
23
def front ( self ) :
" " " Looking at the front element without removing it . " " "
if self . is_empty () :
raise IndexError ( " Queue is empty . " )
return self . _list . head . data
12.4
Binary Search Tree Implementation
A binary search tree is a non-linear data structure where each node has at most two
children. Recursive logic translates very cleanly from C++ to Python.
class TreeNode :
" " " A node in a binary search tree . " " "
3
def __init__ ( self , data ) :
4
self . data = data
5
self . left_child = None
6
self . right_child = None
1
2
7
class BinarySearchTree :
def __init__ ( self ) :
10
self . root = None
8
9
11
12
13
14
def insert ( self , data ) :
" " " Public insert method . " " "
self . root = self . _i nsert_ recurs ive ( self . root , data )
15
16
17
18
def _i nsert_ recurs ive ( self , node , data ) :
" " " Private recursive helper for insertion . " " "
if node is None :
A Developer’s Translation Guide
C++ to Python Guide
43
return TreeNode ( data ) # Base case : create the node here
19
20
if data < node . data :
node . left_child = self . _i nsert_ recurs ive ( node . left_child ,
21
22
data )
elif data > node . data :
node . right_child = self . _i nsert_ recurs ive ( node . right_child ,
data )
23
24
25
# If data is equal , do nothing ( ignore duplicates )
return node
26
27
28
def i n_ or de r_ tr av er sa l ( self ) :
" " " Returns a list of node data in ascending order . " " "
result = []
self . _ in _ o rd e r _r e c ur s i ve ( self . root , result )
return result
29
30
31
32
33
34
def _ in _ o rd e r _r e c ur s i ve ( self , node , result_list ) :
" " " ( Left , Root , Right ) " " "
if node is not None :
self . _ in _ o rd e r _r e c ur s i ve ( node . left_child , result_list )
result_list . append ( node . data )
self . _ in _ o rd e r _r e c ur s i ve ( node . right_child , result_list )
35
36
37
38
39
40
12.4.1 Demonstration of Data Structures
# Linked List Demo
ll = LinkedList ()
3 ll . insert_at_back (10)
4 ll . insert_at_back (20)
5 ll . insert_at_front (5)
6 print ( ll ) # Output : LinkedList : [5 -> 10 -> 20]
1
2
7
# Stack Demo
stack = Stack ()
10 stack . push ( " A " )
11 stack . push ( " B " )
12 print ( f " Popped from stack : { stack . pop () } " ) # Output : B
8
9
13
# BST Demo
bst = BinarySearchTree ()
16 bst . insert (50)
17 bst . insert (30)
18 bst . insert (70)
19 bst . insert (20)
20 bst . insert (40)
21 print ( f " In - order traversal of BST : { bst . in_ or de r_ tr av er sa l () } " )
22 # Output : [20 , 30 , 40 , 50 , 70]
14
15
13
From Templates to Duck Typing
In C++, templates are a powerful feature for generic programming, allowing you to write
functions and classes that can operate on any data type without sacrificing static-type
A Developer’s Translation Guide
C++ to Python Guide
44
safety. Python, being a dynamically-typed language, achieves this same goal of generic
programming through a different, more inherent philosophy known as ”duck typing”.
13.1
The Paradigm Shift: No Templates Needed
Python does not have or need templates in the C++ sense. There is no template
<typename T> syntax. Because variables in Python don’t have fixed types, functions and
classes are generic by default.
13.1.1 Duck Typing
The name comes from the saying: ”If it walks like a duck and it quacks like a duck, then
it must be a duck.”
In Python, this means a function or method does not care about the type of an
object it receives as an argument.
It only cares if the object supports the operations that are performed on it.
For example, a function that uses the + operator on its arguments will work with
integers, floats, strings, or any user-defined class that has an add method.
13.1.2 Functions are Generic by Default
A single Python function can often do the work of multiple C++ template specializations.
// C ++ requires a template for generic addition
template < typename T >
3 T add ( T a , T b ) {
4
return a + b ;
5 }
1
2
6
// And would require separate calls or instantiations
add < int >(5 , 10) ;
9 add < double >(1.1 , 2.2) ;
10 add < std :: string >( " Hello , " , " World ! " ) ;
7
8
# This single Python function is already generic
def add (a , b ) :
3
# It will work as long as the types of ’a ’ and ’b ’
4
# support the ’+ ’ operator .
5
return a + b
1
2
6
7
8
# It works on integers
print ( add (5 , 10) )
9
10
11
# It works on floats
print ( add (1.1 , 2.2) )
12
13
14
# It works on strings
print ( add ( " Hello , " , " World ! " ) )
15
16
17
# It would also work on two lists ( list concatenation )
print ( add ([1 , 2] , [3 , 4]) )
A Developer’s Translation Guide
C++ to Python Guide
13.2
45
Mapping Advanced Template Features
Key Information
Advanced C++ template features generally do not have direct equivalents in Python
because the problems they solve are often non-existent in a dynamic language.
• Nontype Parameters (template<class T, int Size>): This C++ feature allows parameterizing a class with a compile-time constant. Python has no direct
analog. The Pythonic approach is simply to pass such a value (like a size) as a
regular argument to the class’s init constructor at runtime.
• Explicit Specialization (template<> class MyClass<bool>...): C++ allows
providing a completely different implementation for a specific type. In Python, if
you need type-specific behavior, you would handle it inside your methods using a
standard conditional check, typically with isinstance().
Python Code
class MyContainer :
def __init__ ( self , value ) :
3
self . value = value
1
2
4
5
6
7
8
9
10
11
12
def process ( self ) :
# This is the Python way of handling " specializations "
if isinstance ( self . value , bool ) :
print ( f " Specialized bool processing : { self . value } " )
elif isinstance ( self . value , str ) :
print ( f " Specialized string processing : { self . value . upper
() } " )
else :
print ( f " Generic processing : { self . value } " )
13
c1 = MyContainer (100)
c2 = MyContainer ( True )
16 c3 = MyContainer ( " python " )
14
15
17
c1 . process () # Generic processing : 100
c2 . process () # Specialized bool processing : True
20 c3 . process () # Specialized string processing : PYTHON
18
19
13.3
Optional Static Typing with the typing Module
Key Information
While Python is dynamically typed, modern Python (3.5+) allows you to add optional type hints to your code using the typing module.
Key Points:
✓ These are only hints. The Python interpreter does not enforce them at runtime.
Your code will run even if the types don’t match the hints.
A Developer’s Translation Guide
C++ to Python Guide
46
✓ Their primary purpose is to help developers and tools. They improve code readability and allow static analysis tools (like Mypy) and IDEs to catch potential
type-related errors before the code is run.
Success Note
This feature brings some of the clarity of C++’s static typing into Python without
sacrificing its dynamic nature.
Python Code
1
from typing import List , Tuple
2
# This function signature is annotated with type hints
def process_data ( name : str , data : List [ int ]) -> Tuple [ int , float ]:
5
"""
6
This function takes a name ( string ) and a list of integers .
7
It returns a tuple containing an integer and a float .
8
"""
9
total = sum ( data )
10
average = total / len ( data )
11
return total , average
3
4
12
# An IDE or static analyzer could warn you about this next line
# because "123" is not a list of integers .
15 # But the Python interpreter itself will run it and likely fail at
runtime .
16 # process_data (" test " , "123")
13
14
14
Concluding Summary
Key Information
Transitioning from C++ to Python involves more than learning new syntax; it requires a shift in mindset. The core concepts of programming are universal, but their
expression in Python prioritizes developer productivity, readability, and flexibility.
The most significant shifts to remember are:
1. From Static to Dynamic Typing: You declare types in C++; you work with
objects that have types in Python. This makes Python code more concise and generic
by default.
2. From Manual to Automatic Memory Management: The burden of new and
delete is lifted by Python’s garbage collector, eliminating an entire class of common
C++ bugs.
3. From Braces to Indentation: Python enforces clean, readable code structure
through its significant whitespace rules.
A Developer’s Translation Guide
C++ to Python Guide
47
4. From Low-Level to ”Batteries-Included”: Python provides powerful, high-level,
built-in data structures like list and dict that handle most of the complexity you
manage manually with arrays and structs in C++.
Success Note
Your strong foundation in C++ provides you with a deep understanding of how
computers manage data and execute instructions. Python allows you to apply that
understanding at a higher level of abstraction, enabling you to build powerful applications more rapidly. Welcome to the world of Python!
15
The Standard Library: Includes vs. Imports
Key Information
A powerful language is supported by a powerful standard library. In C++, you gain
access to library features by using the #include preprocessor directive. In Python,
you use the import statement. This section maps common C++ headers to their
Python equivalents.
15.1
Philosophy: Minimalist vs. ”Batteries-Included”
• C++ Standard Library: Provides a robust but often considered minimalist set of
tools. It includes fundamental data structures (<vector>, <string>), algorithms
(<algorithm>), and I/O (<iostream>). For more advanced tasks like complex
linear algebra, networking, or advanced file system manipulation, developers often
rely on well-regarded third-party libraries (e.g., Boost, Eigen).
• Python Standard Library: Embodies a ”batteries-included” philosophy. A vast
array of modules for common and advanced tasks is available right after installation.
This includes tools for working with data formats like CSV and JSON, networking, multithreading, interacting with the operating system, and more, all without
needing to install third-party packages.
15.2
Mapping Common C++ Headers to Python Modules
15.2.1 <cmath> (or math.h) → The math Module
Key Information
For standard mathematical operations beyond basic arithmetic, C++ uses <cmath>.
Python provides the math module.
A Developer’s Translation Guide
C++ to Python Guide
48
Operation
C++ (<cmath>)
Python (math module)
Square Root
sqrt(x)
math.sqrt(x)
Power
pow(x, y)
math.pow(x, y) or x ** y
sin(x), cos(x)
math.sin(x), math.cos(x)
Ceiling
ceil(x)
math.ceil(x)
Floor
floor(x)
math.floor(x)
Constant Pi (π)
M PI (often)
math.pi
Sine / Cosine
Python Code
1
import math
2
3
4
x = 16
print ( f " Square root of { x } is { math . sqrt ( x ) } " )
5
6
7
angle_rad = math . pi / 2
print ( f " Cosine of pi /2 is { math . cos ( angle_rad ) } " )
15.2.2 <vector>, <string>, <map>
Success Note
These C++ headers provide core data structures. In Python, their equivalents (list,
str, dict) are built-in types and require no import.
15.2.3 <fstream> and <filesystem> → Built-in open() and the os/pathlib Modules
Key Information
File I/O in Python is handled by the built-in open() function, which is best used
with a with statement for automatic resource management. File system navigation
(listing directories, checking paths) is handled by the standard os and pathlib
modules.
A Developer’s Translation Guide
C++ to Python Guide
49
C++ Code
1
2
# include < fstream >
# include < filesystem > // C ++17
3
void check_file () {
std :: ofstream outfile ( " data . txt " ) ;
6
outfile << " hello " << std :: endl ;
7
outfile . close () ;
4
5
8
if ( std :: filesystem :: exists ( " data . txt " ) ) {
// ...
}
9
10
11
12
}
Python Code
1
2
import os
from pathlib import Path
3
def check_file () :
# ’ with ’ statement handles opening and closing automatically
6
with open ( " data . txt " , " w " ) as f :
7
f . write ( " hello \ n " )
4
5
8
9
10
11
# os module approach
if os . path . exists ( " data . txt " ) :
print ( " File exists ( checked with os ) " )
12
13
14
15
16
# Modern pathlib approach ( often preferred )
p = Path ( " data . txt " )
if p . exists () :
print ( " File exists ( checked with pathlib ) " )
15.2.4 <random> → The random Module
Key Information
Generating random numbers in Python is straightforward with the random module.
A Developer’s Translation Guide
C++ to Python Guide
50
Python Code
1
import random
2
# Generate a random integer between 1 and 100 ( inclusive )
random_int = random . randint (1 , 100)
5 print ( f " Random integer : { random_int } " )
3
4
6
# Generate a random float between 0.0 and 1.0
random_float = random . random ()
9 print ( f " Random float : { random_float } " )
7
8
10
# Choose a random element from a list
choices = [ ’ apple ’ , ’ banana ’ , ’ cherry ’]
13 random_choice = random . choice ( choices )
14 print ( f " Random choice : { random_choice } " )
11
12
15.3
Beyond the Standard Library: The Python AI & Data
Science Ecosystem
Important Note
For a student specializing in AI, the true power of Python comes from its vast
ecosystem of third-party libraries, which are the standard tools of the trade. You
install them using Python’s package manager, pip (e.g., pip install numpy).
Here are the essential libraries that you will use constantly:
⋆ NumPy: The absolute foundation for numerical computing in Python. It provides a powerful N-dimensional array object (ndarray) that is far more efficient
for mathematical operations than a standard Python list. This is the true, highperformance replacement for C++ vectors and arrays in numerical contexts.
⋆ Pandas: The essential library for data analysis and manipulation. It provides the
DataFrame, a two-dimensional labeled data structure like a spreadsheet or SQL
table. It is built on top of NumPy.
⋆ Matplotlib & Seaborn: The primary libraries for data visualization. Matplotlib
is a powerful, low-level plotting library, and Seaborn provides a high-level interface
for creating beautiful statistical graphics.
⋆ Scikit-learn: The most popular library for classical machine learning. It provides
simple and efficient tools for data mining and data analysis, including algorithms
for classification, regression, clustering, and dimensionality reduction.
A Developer’s Translation Guide
C++ to Python Guide
51
15.3.1 A Small Glimpse into the Workflow
Key Information
This brief example shows how these libraries work together in a way that would be
much more complex in C++.
Python Code
1
2
import numpy as np
import pandas as pd
3
# 1. Create a NumPy array with high - performance random data
#
Represents , for example , student grades and study hours
6 data_np = np . random . randint (50 , 100 , size =(5 , 2) )
4
5
7
# 2. Use Pandas to create a labeled DataFrame for easy analysis
#
This is like a spreadsheet in your code
10 df = pd . DataFrame ( data_np , columns =[ ’ Grade ’ , ’ Study_Hours ’ ])
11 df [ ’ Student_ID ’] = [ f ’ id_ {101+ i } ’ for i in range (5) ]
8
9
12
# 3. Perform powerful , high - level analysis
average_grade = df [ ’ Grade ’ ]. mean ()
15 high_achievers = df [ df [ ’ Grade ’] > 85]
13
14
16
print ( " --- Full DataFrame ---" )
print ( df )
19 print ( " \n - - - Analysis Results ---" )
20 print ( f " Average Grade : { average_grade :.2 f } " )
21 print ( " High Achievers : " )
22 print ( high_achievers )
17
18
Success Note
This concise workflow—creating, labeling, and analyzing data—is why Python, with
its powerful libraries, has become the dominant language for data science and AI.
A Developer’s Translation Guide
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )