ToolSphere

Python to C++ Converter

More tools

Convert Python to C++ online: functions, loops, classes and string formatting rewritten as C++. Free, private, runs in your browser.

Verified pairDedicated rewrite rules — syntax, blocks, strings and loops are translated.
Python input
C++ output

AI conversion

For real programs the rules can't handle, translate with Google Gemini: idiomatic C++, imports included, with notes on what to check. This sends the code above to Google, so don't use it for confidential code (privacy). Up to 6,000 characters, 15 conversions a day.

Rewrite rules cover 13 source and 13 target languages (Python, JavaScript, TypeScript, Java, C#, Go, Ruby, PHP, Rust, Kotlin, Swift); the remaining 31 are listed for reference and pass through annotated rather than translated. Complex projects still need manual review. The rule-based conversion runs entirely in your browser; only the optional AI conversion sends code anywhere.

On this browser only

Give feedback

Did this tool help?

Tell us what worked, what didn’t, or what you’d like next.

Opens Google Forms in a new tab with this tool’s name filled in. No sign-in or email required. Feedback is optional.

How to use Python to C++ Converter

  1. 1Choose the source and target programming languages from the dropdowns.
  2. 2Paste your source code into the left editor (or click Load sample).
  3. 3Review the converted output on the right; use Copy or Download to export.
  4. 4Swap languages to reverse the conversion direction when supported.

About Python to C++ Converter

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.

Frequently asked questions

How reliable is Python to C++ conversion?

This is one of the converter's directly supported pairs, so everyday syntax — functions, classes, loops, conditionals and string formatting — translates cleanly. Library and framework calls still need manual work, since only language syntax is mapped.

Is my source code uploaded to a server?

Not by the converter itself: the rule-based conversion runs entirely in your browser. Only if you press Convert with AI is the code sent to Google Gemini for translation, so keep confidential code to the rule-based converter.

How accurate is automatic code conversion?

Popular pairs (Python, JavaScript, Java, Go, C#, etc.) use dedicated rewrite rules. Other pairs may use a JavaScript pivot or annotated passthrough — always review before production use.

Can I convert entire projects?

This tool is optimized for snippets, homework samples, and algorithm ports. Multi-file projects need manual structure and import adjustments.

Does this support every Python library?

No. Standard language syntax is mapped; framework-specific APIs must be rewritten manually in C++.

Does the converted C++ compile?

For typical homework programs, yes: the converter is tested by compiling programs with loops, lists, dictionaries, input, f-strings, classes and exceptions, and checking that each prints the same output as Python. Anything it cannot translate is left as a TODO comment rather than a guess, so fix those lines first.

Which C++ standard does the output need?

C++20, because parameters whose type cannot be inferred become auto parameters. Compile with g++ -std=c++20 main.cpp -o main, clang++ -std=c++20, or /std:c++20 in Visual Studio.

How does the converter choose C++ types?

From literals, type hints, default values and use: 5 becomes int, 2.5 double, "text" string, and an empty list takes its element type from what is appended to it. Parameters with nothing to go on become auto. Check the types against your real data, especially for large numbers.

How are input() and print() converted?

int(input()) and float(input()) become cin reads, input() becomes getline, and map(int, input().split()) reads several numbers from one line. print becomes a cout chain that keeps sep, end and f-string formatting, and floats and booleans print the way Python prints them.

Can it convert Python classes to C++?

Simple classes, yes: __init__ becomes a constructor, self.x fields become members with inferred types, and methods become member functions. Inheritance beyond a base name, special methods like __str__ and properties are left for you to finish.

Why does my converted program give different numbers?

Usually integer limits or negative division. Python integers never overflow while C++ int is 32-bit, so use long long for big values; and // and % round differently for negative numbers in C++.

Have a suggestion for Python to C++ Converter?Share your feedback ↗