是否可以在while循环内进行睡眠功能?我有这个while循环到无限。当我添加time.sleep(10)
时,它将在第二次尝试后跳出循环。是否可以在无限循环内time.sleep()
?
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)
答案 0 :(得分:1)
您发布的代码可以正常工作。当用户输入的内容不完全是int时,可能会引起问题(如@Guy所述)。这是因为input
返回一个字符串,而int
试图从该字符串中获取一个整数,例如in。如果无法读取int
,则会引发ValueError
。例如
>>> 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'
因此,您需要通过try except
块来明确处理这种情况
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)