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:
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
"""
Multiline comment
"""
Whitespace and identation matters
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.
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>
x = 5
x = 5.2
x = 4+2j
X = True
x = "Hello"
x = 'Hello'
x = ["Hello","There",5]
x = ("Hello","There",5)
x = {"a","b","c"}
x = {"a1":"b","a2":"c","a3":"d"}
x = 5
y = float(x)
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:
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:
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++:
std::vector<int> ints = {1,2,3};
for(auto i : ints)
{
printf("%d",i);
}
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
if i > 5:
pass
This keyword can be used in functions and classes as well.
a = ...;
switch(a)
{
case 5:
result = 1;
break;
}
a = ...
match a:
case 5:
result = 1
Operators
In addition to the common C++ operators (+*/- etc), Python has two interesting ones:
x = 5
y = 3
z = x/y
z = x//y
z = x**y
The logical && || and ! in C++ are "and", "or" and "not" in Python
Functions
def fn_name(a,b = "Default_value"):
print("Hello",a,b)
fn_name(1)
fn_name(2,"Hello")
def fn2(*k):
print(k)
fn2("Hello","There")
fn_name(a = 5,b = 3)
fn_name(b = 4,a = 1)
def fn3(**k):
print(k["King"])
fn3(Hello = "There",King = "Michael")
Python also has lambda functions which only support one statement inside them.
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.
names = ["Michael","George","John"]
x = names[0]
x = names[-1]
names2 = ["Michael",["Jack","Peter"],"George","John"]
x = names2[1][1]
names3 = names[0:1]
names3.append("Johanna")
names3.extend(["Paul","Cath"])
del names3[0]
print("Cath" in names3)
The same array access elements like [0],[0:1],[-1] also apply to strings.
Exception handling
FILE* fp = 0;
fopen_s(&fp,"test.txt","r");
try
{
fwrite(fp,1,1,"x");
}
finally
{
fclose(fp);
}
with open("test.txt", "r") as infile:
content = infile.read()
...
lock = threading.Lock()
with lock:
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++.
def mulf(a,b):
return a*b;
import m
y = m.mulf(1,5)
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
class Animal:
def __init__(self,name,age = 2):
self.animal_name = name
self.__animal_age = age
def printme(self):
print(self.animal_name)
def __add__(self, other):
return Animal(self.name + other.name);
a = Animal("Leopard")
a.printme()
print(a.animal_name)
b = Animal("Elephant")
c = a + b
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 !=.
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