Slartibartfast
Slartibartfast

Reputation: 1200

Sleep() function inside a infinite while loop

Is it possible for sleep function inside a while loop? I have this while loop which goes to infinity. When I add time.sleep(10) it breaks out of the loop after the second try. Is it possible to time.sleep() inside an infinite loop?

import time as time
while True:
    for i in range(2):
       num = int(input("Enter an integer: "))
       print("The double of",num,"is",2 * num)
    print('10')
    time.sleep(10)

Upvotes: 0

Views: 1209

Answers (1)

Fakher Mokadem
Fakher Mokadem

Reputation: 1099

The code as you post it works just fine. The problem may (as mentioned by @Guy) be cause when the user inputs something that is not exactly an int. That is because input returns a string and int tries to get an integer out of that string e.g. in. On failing to read int raises a ValueError. e.g.


>>> num = input("Enter an integer: ")
Enter an integer: 12.5
>>> num 
'12.5'  <-- num, the return of input is a string
>>> int(num) <-- int fails to get a integer out of the string num
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12.5'   

So you need to handle that case explicitly by a try except block


import time as time
while True:
    for i in range(2):
       try: 
           num = int(input("Enter an integer: "))
           print("The double of",num,"is",2 * num)
       except ValueError: 
           print("Please enter a valid integer")
    print('10')
    time.sleep(10)

Upvotes: 1

Related Questions