Click here to Skip to main content
16,004,557 members
Articles / Programming Languages / Python

From C++ to Python: Get Closer

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
20 Sep 2024CPOL3 min read 8.4K   14   6
A quick python course for C++ developers
If you know C++, then you will just see how Python works.

Introduction

If you know C++ well, learning any other language is really simple. So lets take a look at Python, the most modern machine learning tool we have today. 

Not that there aren't libraries in C++ but they are a lot lower level that what we need to do. Just take a look at my machine learning article with DirectML and compare it with torch way to send a tensor to the GPU: 

Python
a = torch.LongTensor(1).random_(0, 10) 
a = a.to(device="cuda")

When doing stuff like machine learning, we are not pretty much interested on writing a 200-line SQLite3 wrapper just to load a database into memory or create a tensor class from scratch to manipulate it. You also need heavy multithreading and synchronization, database access and quick math stuff. Python is a lot easier for that.

Python 3

I'm not going to refer to Python 2 which has some incompatibilities with version 3 (for example, in Python 2, strings are not unicode by default). I'm focusing always on Python 3.

Portable Installation

Take a look at WinPython for windows to get a portable installation for whatever version you want. For extra options you can also use conda via MiniConda.

Comments

Python
# Single line comment 
""" 
Multiline comment 
""" 

Whitespace and identation matters

Python
x = 5
if x == 5:
    print("hello")

In Python, you don't need the semicolon to mark the end of line, so you need the \n. Also, there are no { and }'s, so you need the identation to mark what would be a {} section. Also, Python uses ':' to mark the end of anything that would next had a { in C++ (if/while/function/class).

Identation is mandatory in Python, so everything after if, function, class etc where you would use the { and } in C++ must be indented or you will get an error.

Variable usage

Like PHP, you don't need a typed declaration. Python variables are dynamically created as needed.

Python
x = 5
y = 10
z = int(input("Enter a number:"))
e = x + y + z
if e == 10:
   print("10")
else:
   print("Not 10")

Consider Python variables as std::any in C++ with dynamic storage. 

Data types

You have

  • int as long long
  • float as double
  • complex (no direct equivalent in C++)
  • bool as bool
  • str as std::string
  • lists as std::vector<std::any>
  • tuples as const std::vector<std::any>
  • sets as std::set<std::any>
  • dictionaries as std::map<std::any>
Python
# int
x = 5
# float
x = 5.2
# complex
x = 4+2j
# bool
X = True
# str
x = "Hello"
x = 'Hello' # equal
# list
x = ["Hello","There",5]
# tuple
x = ("Hello","There",5)
# set
x = {"a","b","c"}
# dict
x = {"a1":"b","a2":"c","a3":"d"} # like Json

# some casting
x = 5
y = float(x)
# multiple assignment
a,b,c = "1","2","3"

Strings can either use double quote or single quote and are unicode. Tuples are immutable. 

Flow control

Python has if, elif, else, while and for.  The double colon : marks the end of the expression:

Python
if x > y:
   print("Hello")

After while, we can have an else to execute code when the while is not true or no longer true:

Python
while x > y: 
    y++;
else:
    print("x no longer larger than y")

 For loops in Python are only valid for looping sets, so it's like for(auto& x : container) in C++:

C++
std::vector<int> ints = {1,2,3};
for(auto i : ints)
{
 printf("%d",i);
}
Python
ints = [1,2,3]
for i in ints:
 print(i)

If you want an empty statement for some reason, like if () {} in C++, use the pass keyword

Python
if i > 5:
  pass

This keyword can be used in functions and classes as well.

C++
a = ...;
switch(a)
{ 
  case 5: 
    result = 1;
    break;
}
Python
a = ...
match a:
 case 5:
  result = 1
  

Operators

In addition to the common C++ operators (+*/- etc), Python has two interesting ones:

Python
x = 5
y = 3
z = x/y # result = float
z = x//y # result = int
z = x**y # equal to pow(x,y)

The logical && || and ! in C++ are "and", "or" and "not" in Python

Functions

Python
def fn_name(a,b = "Default_value"):
  print("Hello",a,b)

# call it
fn_name(1)
fn_name(2,"Hello")

# variant number of arguments
def fn2(*k): # now k will be a tuple
 print(k)

fn2("Hello","There")

# named arguments call
fn_name(a = 5,b = 3) # equal to fn_name(5,3)
fn_name(b = 4,a = 1) # equal to fn_name(1,4)

# dictionary call
def fn3(**k): # now k will be a dict
 print(k["King"])

fn3(Hello = "There",King = "Michael")

Python also has lambda functions which only support one statement inside them.

Python
def f1(a,b):
 multwo = lambda c,d : c*d
 return multwo(a,b)

If you create a global variable and then, in a function, you have a local variable, it behaves like C++, the global variable becomes invisible.

Arrays

There are no "low-level" arrays, use lists instead.

Python
names = ["Michael","George","John"]
x = names[0] # x = "Michael"
x = names[-1] # x = "John"

names2 = ["Michael",["Jack","Peter"],"George","John"]
x = names2[1][1] # x = "Peter"

names3 = names[0:1] 
# names3 = ["Michael","George"]

names3.append("Johanna") 
# names3 = ["Michael","George","Johanna"]

names3.extend(["Paul","Cath"]) 
# names3 = ["Michael","George","Johanna","Paul","Cath"]

del names3[0]
# names3 = ["George","Johanna","Paul","Cath"]

print("Cath" in names3) # prints True

The same array access elements like [0],[0:1],[-1] also apply to strings.

Exception handling

C++
FILE* fp = 0;
fopen_s(&fp,"test.txt","r");
try
{ 
    fwrite(fp,1,1,"x");
}
finally
{
    fclose(fp);
}
Python
with open("test.txt", "r") as infile: 
    content = infile.read()

...


lock = threading.Lock()
with lock:
    # Critical section of code

In Python, the with keyword automatically releases stuff at the end of its block. It is the RAII (Resource acquisition is initialization) C++ model which safely releases objects when needed. See more in this StackOverflow question.

Modules

A module is a .py file which you can then refer from another Python file, like namespaces in C++.

Python
# m.py

def mulf(a,b):
 return a*b;

# project.py
import m
y = m.mulf(1,5)

# project2.py
import m as mm
y = mm.mulf(10,11)

Pip installs  many ready-to-be-used modules in Python, as you probably already know by now.

Objects

Python
# class example
class Animal:
 # constructor
 def __init__(self,name,age = 2):
   self.animal_name = name # this->animal_name = name;, creates a public member "animal_name"
   self.__animal_age = age # creates a non-public member "animal_age"
 # member function
 def printme(self):
   print(self.animal_name)
 # operator overloading
 def __add__(self, other):
   return Animal(self.name + other.name); 

# use it
a = Animal("Leopard")
a.printme()
print(a.animal_name)
b = Animal("Elephant")
c = a + b # LeopardElephant (duh:)

Default access for variables is "public" and you can use two underscores to make it private. There are also other "special" overloads like __sub__, __pow__ etc. __lt__(), __le__(), __gt__(), __ge__(), __eq__(), __ne__()  overload <, <=, >, >=, == and !=.

Python
# Inheritance
class FastAnimal(Animal):
 def __init__(self,name,age,speed):
  super().__init__(name,age)
  self.speed= speed

Contrary to C++, you can omit calling the parent constructor. In this case, the parent variables are not there. super() is used to access the superclass' data.

That's it for now. Keep going!

History

20-9-2024: Fixed typos, added installation methods.

7-4-2024: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Greece Greece
I'm working in C++, PHP , Java, Windows, iOS, Android and Web (HTML/Javascript/CSS).

I 've a PhD in Digital Signal Processing and Artificial Intelligence and I specialize in Pro Audio and AI applications.

My home page: https://www.turbo-play.com

Comments and Discussions

 
QuestionFunctions with variable assign lambda Pin
NunoPereira13-Sep-24 6:55
NunoPereira13-Sep-24 6:55 
PraiseGood Article Pin
Praveen Kumar Katiyar12-Jul-24 17:32
professionalPraveen Kumar Katiyar12-Jul-24 17:32 
QuestionMinor error ... Pin
Richard MacCutchan8-Jul-24 1:20
mveRichard MacCutchan8-Jul-24 1:20 
AnswerRe: Minor error ... Pin
Michael Chourdakis13-Jul-24 5:06
mvaMichael Chourdakis13-Jul-24 5:06 
GeneralThanks Pin
Marat Shaimuratov4-Jul-24 20:55
Marat Shaimuratov4-Jul-24 20:55 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA3-Jul-24 17:25
professionalȘtefan-Mihai MOGA3-Jul-24 17:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.