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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)