• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • About
  • Life
  • Tech
  • Travel
  • Work
  • Questions
  • Contact

Welcome

.

C++ for-loop vs. Python for-loop

April 10, 2020 by

Questions › C++ for-loop vs. Python for-loop
0
Vote Up
Vote Down
Garmaine asked 4 years ago

I'm currently learning Python as I'm taking a data mining class. I was making a for-loop to make a noisy data file to do smoothing and I found a peculiarity on Python for-loop that I couldn't understand nor go around.

So I made this simple testing C++ and Python codes. C++ one works, but Python one doesn't.

The reason is that C++ allows arbitrary updates on the counter variable i within the for-loop block, but Python doesn't.

On Python code, I try to update i arbitrarily by doing i += 1 within the while-loop, but if you look at the outputs for At the first part of the loop, i = SOMETHING, Python is arbitrarily updating the i only in the while-loop that's in the for-loop, but then reverts the value back when it exits that while-loop. (Outputs are in the comments at the bottom)

Why is that? Is it a scope issue? (Both C++ and Python are statically scoped) Is it because of their types? (I'm only familiar with statically-typed languages like C++ and Java, and not dynamically-typed languages like Python)

On Python, it seems like the for-loop is actually a function with return-by-value parameter i which ignores all the changes on the parameter that took place inside the function.

I tried:

  • Setting the counter i as a global variable.
  • using range(0, len(input), *variable*), but I still failed to replicate it.
  • Researched if it can be solved by using Static variable or similar sort on Python (I think it's irrelevant?)

On Python, how would you replicate this C++ code? Could you enlighten me on why those for-loops behave differently? Thank you.

This is C++ code that's working correctly:

#include <stdio.h>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    string input = "abc defg";
    string eachWord = "";

    for(int i = 0; i < input.length(); i++)
    {
        cout << "At the first part of the loop, i = " << i << " ." << endl;

        while(input[i] != ' ' && input[i] != '\0')
        {
            eachWord += input[i];
            i++;
        }

        cout << eachWord << endl;
        cout << "At the last part of the loop, i = " << i << " ." << endl << endl;
        eachWord = "";
    }
}

/*
Output:
At the first part of the loop, i = 0 .
abc
At the last part of the loop, i = 3 .

At the first part of the loop, i = 4 .
defg
At the last part of the loop, i = 8 .
*/

And this is the Python code that's not working correctly, that I tried to make to replicate the C++ code:

input = "abc defg"
eachWord = ''

for i in range(len(input)):
    print("At the first part of the loop, i = ", i, ".")
    while(input[i] != ' ' and input[i] != '\0'):
        eachWord += input[i]
        i += 1

    print(eachWord)
    print("At the last part of the loop, i = ", i, ".")
    print()
    eachWord = ''

"""
Output:
At the first part of the loop, i =  0 .
abc
At the last part of the loop, i =  3 .

At the first part of the loop, i =  1 .
bc
At the last part of the loop, i =  3 .

At the first part of the loop, i =  2 .
c
At the last part of the loop, i =  3 .

At the first part of the loop, i =  3 .

At the last part of the loop, i =  3 .

At the first part of the loop, i =  4 .
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    while(input[i] != ' ' and input[i] != '\0'):
IndexError: string index out of range
"""
Are you looking for the answer?
Original Question and Possible Answers can be found on `http://stackoverflow.com`

Question Tags: c++, for-loop, python

Please login or Register to submit your answer




Primary Sidebar

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Newsletter

Complete the form below, and we'll send you all the latest news.

Footer

Footer Funnies

Who knew that reading the footer could be such a hilarious adventure? As we navigate websites, books, and documents, we often stumble upon the unassuming space at the bottom, only to discover a treasure trove of amusement. In this side-splitting compilation, we present 100 jokes that celebrate the unsung hero of content – the footer. Get ready to chuckle, giggle, and maybe even snort as we dive into the world of footnotes, disclaimers, and hidden comedic gems. Brace yourself for a wild ride through the footer!

Recent

  • Unveiling the Enigma: Almost-Magical Lamp Lights Highway Turns
  • The Impact of Young Onset Dementia on Employment and Finances: Optimizing Post-Diagnostic Approaches
  • 11 Wonders of 2023 Technological Breakthrough – Unveiling the Future
  • Work from Home and Stay Mentally Sane – Achieve Productivity and Well-being
  • Hidden Gems of New York City – Uncover the Must-See Treasures!

Search

Tags

Advancements best Business strategies commercial convenience economic Finances Cognitive decline Financial growth firm Future Hidden Gems Home hydration Impact Innovations lighting line of work Mental health Must-See New York City office patronage Productivity profession Profitability tips Profit optimization pursuit recreation Revenue enhancement romance sippy cups social station Technological breakthroughs technology toddlers trading transaction Treasures Uncover undertaking Well-being Wonders Work Young onset dementia

Copyright © 2023