I want to loop this, and everytime it loops I want 1 so it prints ( 1 2 3 4 5.. untill infinite) But it prints 1 2 1 2 1 2 1 2 ... what am i doing wrong? code:
import time
x = 1
def main():
print(x)
x 1
time.sleep(1)
print(x 1)
main()
main()
CodePudding user response:
Inside the function when you are adding x 1
you are not storing the value back in x to update it. Here is a better implementation.
import time
x = 1
def main():
global x
print(x)
x = 1
time.sleep(1)
while True:
main()
CodePudding user response:
You can use an iterator.
By using next()
you can ask it what the next number would be and they only get calculated once you actually need them. The limit ist the system size of python-integers in this example.
import sys
maxSize = sys.maxsize
i = iter(range(maxSize))
def main():
print(next(i))
main()
# 0
main()
# 1
main()
# 2
CodePudding user response:
Your code says main does -> print 1, 2, sleep, print 2.
You should do
x = 1
def main():
while true:
print(x)
x = 1
time.sleep(1)
main()
Your original code doesn't alter x. x = 1 means x = x 1.
x 1 is just 2. And that 2 doesn't get stored anywhere. And to go on infinitely you just leave a while true loop running and manually kill the code. Although you could put some cap on it like 1000 loops.
CodePudding user response:
The mistake here is that you're restarting x every time you're caling the function main() beccause there is no loop.
def main():
x = 1
while True:
print(x)
time.sleep(1)
x = 1
main()