DEV Community

Cover image for C++ vs Python For Loops
Kit Oster
Kit Oster

Posted on

C++ vs Python For Loops

The very first programming language I interacted with was C++, and that became the language through which I thought about loops. Seeing my first Python for loop was a scary experience, which was surprising as I had always heard Python described as friendly!

Let's take a look at the same loops in C++ and Python 3. The following C++ and Python code will both loop through an array of three fruits.

C++

Image description

Python

Image description

Both of these will output the following:
Apple
Banana
Cherry

Some key differences here are that we have to explain what we want to do a little bit more with C++. Statement 1 is used to set a variable before the loop starts (int i=0), statement 2 will gives the condition for the loop to run, and statement 3 increments or decrements the variable. Python is much less wordy.

To print the numbers 0 through 5, all we would have to do in Python is the following:

Image description

And this will output
0
1
2
3
4
5

Whereas in C++, we would do something like this:

int main() {
for (int i = 0; i < 6; i++) {
cout << i << "\n";
}
return 0;
}

Though switching to Python felt like a big change at first, I soon realized how intuitive it is. Python is flexible, powerful, and easy to learn, making it a great choice for first-timers or experienced programmers looking for a change of pace.

Image of Datadog

Optimize UX with Real User Monitoring

Learn how Real User Monitoring (RUM) and Synthetic Testing provide full visibility into web and mobile performance. See best practices in action and discover why Datadog was named a Leader in the 2024 Gartner MQ for Digital Experience Monitoring.

Tap into UX Best Practices

Top comments (0)

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay