【问题标题】:Sleep() function inside a infinite while loop无限while循环内的Sleep()函数
【发布时间】:2020-03-17 06:23:08
【问题描述】:
可以在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)
【问题讨论】:
标签:
python
python-3.x
while-loop
sleep
【解决方案1】:
您发布的代码运行良好。当用户输入不完全是 int 的内容时,问题可能(如 @Guy 所述)是原因。这是因为input 返回一个字符串,而int 尝试从该字符串中获取一个整数,例如中。在未能阅读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)