-2

My C++ is functioning as expected but the equivalent Python code hangs in an infinite loop. Help!

C++

#include <iostream>

using namespace std;

int main()
{
    for(int i=0;i<4;++i){

        int j=0;

        while(i!=j){
            ++j;
            cout<<j<<endl;
        }
    }
}

Python

for i in range(4):

    j = 0

    while i != j:

        ++j

        print(j)
Bilal Siddiqui
  • 349
  • 3
  • 17
  • 3
    Please don't get into the habit of doing line-by-line translations from one language like C++ to another, and vice-versa. Learn the language as if the other language doesn't exist. – PaulMcKenzie Nov 24 '18 at 03:39
  • Paul has a point ... or many ...what is the purpose of the loop? – Ted Lyngmo Nov 24 '18 at 03:40
  • Well, I did try += as well but it didn't work in the original implementation for some reason. At least now I know why python doesn't use increment operator haha. – Tejas Pandey Nov 24 '18 at 03:44
  • possible duplicate: [Why are there no ++ and --​ operators in Python?](https://stackoverflow.com/q/3654830/995714), [Python integer incrementing with ++](https://stackoverflow.com/q/2632677/995714), [in python, ++x is correct syntax. What does "++x" mean?](https://stackoverflow.com/q/11209899/995714), [Does Python support ++?](https://stackoverflow.com/q/13229760/995714), [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/q/1485841/995714) – phuclv Nov 24 '18 at 04:05
  • Possible duplicate of [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python) – ead Nov 29 '18 at 07:26

2 Answers2

5

++j is not a thing in Python. You want j += 1.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • I wasted too much time on this... – Tejas Pandey Nov 24 '18 at 03:40
  • @TejasPandey why don't you read the interpreter error? Googling for things like `python "++" syntax error` would give you a lot of answers immediately: [Python integer incrementing with ++](https://stackoverflow.com/q/2632677/995714), [in python, ++x is correct syntax. What does "++x" mean?](https://stackoverflow.com/q/11209899/995714), [Does Python support ++?](https://stackoverflow.com/q/13229760/995714)... – phuclv Nov 24 '18 at 04:02
  • I got an infinite loop so no error. – Tejas Pandey Nov 24 '18 at 04:52
0

In order to avoid ambiguity/confusion, our Benevolent Dictator For Life thought to not allow ++ or -- into the Python ecosystem. That means you are in an infinite loop because ++j does not do what you believe it to do.

Bilal Siddiqui
  • 349
  • 3
  • 17
  • Well my understanding now is that all variables are immutable so you can't do ++. They are immutable because of how python handles datatypes. `x = 5` `x++` makes sense `x = 'blah'` `x++` doesn't make sense. – Tejas Pandey Nov 24 '18 at 17:44