“不明白这段代码有什么问题”

时间:2019-10-08 15:12:35

标签: python-3.x while-loop

while循环应该进入else语句。但是它始终变为True,在21岁时没有进入else语句,

import time
from datetime import datetime as dt

hosts_temp="hosts"
hosts_path=r"C:\WINDOWS\System32\drivers\etc\hosts"


redirect="127.0.0.1"
website_list=["www.facebook.com", "facebook.com","www.youtube.com", "youtube.com"]

while True:
    if dt(dt.now().year,dt.now().month,dt.now().day,16) < dt(dt.now().year,dt.now().month,dt.now().day,18):
        print("Working Hours,,,,,,,,.......!!")
        with open(hosts_temp,"r+") as file:
            content=file.read()
            for websites in website_list:
                if websites in content:
                    pass
                else:
                    file.write(redirect+"       "+websites+"\n")
    else:
        with open(hosts_temp,"r+") as file:
            content=file.readlines()
            file.seek(0)
            for line in content:
                if not any(websites in line for websites in website_list):
                    file.write(line)
            file.truncate()
        print("Fun time.......")
    time.sleep(5)

我希望它转到else语句

1 个答案:

答案 0 :(得分:-1)

在python中,while循环具有以下语法:

while (condition):

您将条件设置为“ true”;因此,这将永远是正确的。你知道我的意思吗?

这是经典的例子:

i = 1
while i < 6:
  print(i)
  i += 1

此打印:

> 1
> 2
> 3
> 4
> 5

因为条件(i <6)仅在i变为6时才成立。