-1

I have this code in C

int main(){
    int t = 1;
    while(t != 0)
        t = t + 1;
    return 0;
}

What would be the equivalent in Python?

In C, although it appears as such, it's not an infinite loop. Would it be similar in Python?

DYZ
  • 55,249
  • 10
  • 64
  • 93
Jonath P
  • 519
  • 5
  • 16
  • 1
    I'm voting to close this question as off-topic because SO is not a tutorial service. OP should check the official Python document and other tutoring sites. – Moinuddin Quadri Jan 22 '17 at 06:55
  • 1
    Since this C program exhibits undefined behavior, it isn't clear what Python program the author is asking for. Jonath, what precisely do you think this program does? – Robᵩ Jan 22 '17 at 07:04
  • Given [this response about Max value of integers in Python](https://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints), I'm going to say the behaviour will be different. – AntonH Jan 22 '17 at 07:07
  • I'm voting to close this question as off-topic because you should only ask practical, answerable questions based on actual problems that you face. – Robᵩ Jan 22 '17 at 07:10
  • @MoinuddinQuadri: I agree stackoverflow isn't a tutorial, but if I don't know what to look for in the tutorial, well that's a problem I'm facing and that other people can help me with. – Jonath P Jan 22 '17 at 07:35
  • 1
    @Robᵩ : As I understood it, this code enumerates all intergers that can be represented. I had tried to simply reformulate it in Python, but it was an endless loop, so I wondered if there was something I missed or if it didn't operate the same way. – Jonath P Jan 22 '17 at 07:37
  • 1
    @JonathP Not an endless loop, but the values for integers in Python aren't the same as in C, so it would take much longer to run through, and feel infinite if you don't leave it long enough. – AntonH Jan 22 '17 at 07:46

3 Answers3

2

Python integers are not limited in constant number of bytes, only in your RAM limits. This loop would go forever, until your computer runs out of memory.

Use sys.getsizeof(int()) and sys.getsizeof(int(2**128)) to test this behaviour.


Anyway, the equivalent that terminates is

t = 1
while t < 2**32:
    t += 1

(Considering 32-bit integers)

Uriel
  • 15,579
  • 6
  • 25
  • 46
0

like this?:

def main():
    t = 1
    while t != 0:
        t += 1
    return 0

main()
DYZ
  • 55,249
  • 10
  • 64
  • 93
Knight-Zhou
  • 49
  • 1
  • 7
0

You can try this with numpy:

import numpy as np
t = (np.int16)(1)
while t != 0: 
    print t
    t += (np.int16)(1)
print t
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63