Python to C++ Code Converter
Port algorithms, interview snippets, and learning examples from Python to C++ without installing anything. The rule-based converter runs locally in your browser, so code stays private; for larger programs, the optional Convert with AI button produces an idiomatic C++ translation with notes on what to check.
Typical use cases: migrating utility scripts, comparing syntax across languages, preparing C++ stubs from Python prototypes, and speeding up CS homework refactoring.
Select your languages, paste code, and iterate with swap-and-edit until the output matches your target idioms.
Python to C++ uses dedicated rewrite rules. This pair has hand-written rules rather than a generic fallback: block structure, string literals, loops, conditionals and function declarations are translated directly from Python into C++ idioms.
Python types and their C++ equivalents
| Python | C++ | Watch out for |
|---|---|---|
int |
int or long long |
Python integers never overflow; int is usually 32-bit |
float |
double |
Same IEEE 754 precision |
str |
std::string |
Indexing gives bytes, not Unicode characters |
bool, None |
bool, std::optional<T> or nullptr |
|
list[int] |
std::vector<int> |
len(xs) becomes xs.size() |
dict[str, int] |
std::unordered_map<std::string, int> |
Use std::map if you need keys in sorted order |
set, tuple |
std::unordered_set, std::tuple / std::pair |
|
print(a, b) |
std::cout << a << " " << b << "\n"; |
|
f"{x:.2f}" |
std::format("{:.2f}", x) (C++20) |
Or std::setprecision with streams |
Worked example: counting words
def word_counts(words):
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
for word, n in word_counts(["to", "be", "or", "not", "to", "be"]).items():
print(word, n)
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
std::unordered_map<std::string, int> word_counts(const std::vector<std::string>& words) {
std::unordered_map<std::string, int> counts;
for (const auto& w : words) {
counts[w] += 1; // operator[] starts a missing key at 0, like counts.get(w, 0)
}
return counts;
}
int main() {
for (const auto& [word, n] : word_counts({"to", "be", "or", "not", "to", "be"})) {
std::cout << word << " " << n << "\n";
}
}
Three things changed beyond syntax: every variable and return value has a type, the list is passed by const reference so it is not copied, and the dictionary became an unordered_map, so the words come out in no particular order (Python keeps insertion order). Compile with g++ -std=c++17 -O2 main.cpp -o main; the for (const auto& [word, n] : …) loop needs C++17.
What the converter does with your code
Paste this Python on the left:
marks = []
for i in range(3):
m = int(input())
marks.append(m)
avg = sum(marks) / len(marks)
if avg >= 75:
grade = "Distinction"
else:
grade = "Pass"
print(f"Average: {avg:.1f}, {grade}")
The converter writes a complete C++ program: the #include lines it needs, small helper functions such as fixed_str and sum_of only when the program uses them, and this main:
int main() {
string grade{};
vector<int> marks;
for (int i = 0; i < 3; i++) {
int m;
cin >> m;
marks.push_back(m);
}
double avg = (double)sum_of(marks) / (int)marks.size();
if (avg >= 75) {
grade = "Distinction";
} else {
grade = "Pass";
}
cout << "Average: " << fixed_str(avg, 1) << ", " << grade << endl;
return 0;
}
Compiled with g++ -std=c++20 and given 70, 82 and 91, both versions print Average: 81.0, Distinction. Notice what changed: input() became cin, the empty list became a vector<int> because an int is appended to it, / kept Python's true division with a (double) cast, and grade is declared before the if because C++ variables only live inside the block that declares them.
What it translates: functions (including default arguments and type hints), if/elif/else, for over range, lists, strings, enumerate and dict.items(), while, break/continue, lists and nested lists, dictionaries as std::map, input() including map(int, input().split()), print with sep and end, f-strings with :.2f, tuple assignment and swaps, raise/try/except, and simple classes with __init__ and methods (as a struct). Floats and booleans are printed the way Python prints them, so 80.0 stays 80.0 and True stays True.
What it leaves as // TODO comments rather than guessing: list comprehensions, lambdas, generators, with blocks, zip loops, *args, finally and special methods such as __str__. Parameters with no hint or default become C++20 auto parameters (passed by reference when the function changes a list in place, as Python callers would see). Python integers never overflow and C++ int is 32-bit, and // and % match Python only for non-negative numbers; the header comment of every conversion says so.
Rules or AI?
The rule-based converter runs instantly in your browser and is built for homework-sized programs: the test suite compiles more than twenty typical programs and checks that each prints exactly what Python prints. For a real program with libraries, generators or comprehensions, press Convert with AI for an idiomatic translation with notes on what to check, then compile it and test it against the Python output.
Classes: Python to C++
class Account:
def __init__(self, owner, balance=0.0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
#include <stdexcept>
#include <string>
#include <utility>
class Account {
public:
explicit Account(std::string owner, double balance = 0.0)
: owner_(std::move(owner)), balance_(balance) {}
void deposit(double amount) {
if (amount <= 0) throw std::invalid_argument("amount must be positive");
balance_ += amount;
}
double balance() const { return balance_; }
private:
std::string owner_;
double balance_;
};
self.x becomes a member variable declared once in the class, __init__ becomes a constructor with an initialiser list, raise becomes throw, and the fields are private with a getter because C++ code usually hides state that Python leaves open.
Compile errors you will see first
| Error | Usual cause after converting | Fix |
|---|---|---|
'x' was not declared in this scope |
A Python variable first assigned inside an if or loop |
Declare it before the block |
no matching function for call |
Mixed types, such as int passed where std::string is expected |
Match the parameter types, or add a conversion |
'cout' is not a member of 'std' |
Missing header | Add #include <iostream> (and <vector>, <string> as needed) |
| Wrong results, no error | Integer division: 7 / 2 is 3 in C++ |
Make one side a double |
| Crash or garbage values | Indexing past the end; C++ does not check v[i] |
Use v.at(i) while testing |
Is the C++ version faster?
Usually, by a lot, for loops over numbers and strings: compiled C++ skips the interpreter. Code that spends its time in NumPy, pandas or other C-backed libraries gains much less, because that work already runs as compiled code. Convert the hot loop, measure, and keep the rest in Python if it isn't the bottleneck.