简体   繁体   中英

Use a variable, that is in a while loop, in an if statement python

import datetime


time = datetime.datetime.now()
hm = 0

def function():

    while True:
        hm = (time.hour, time.minute)
        break

    if hm == (6,30):
        "stuff"
        function()

    else:
        "stuff"

My goal is to get the time and then do something once it reaches a certain time. My editor gives me an error saying the code is unreachable. I don't know what to do since I cannot return a variable in a while loop. Thanks.

You don't have any break statement in the Loop. The if/else is outside of the loop's scope. You need to indent it, and add some break statements.

I'd skip the while loop and go with an approach more like this (if you don't want to use a library):

import datetime
import time

start_time = datetime.datetime.now()
end_time = start_time.replace(hour=18, minute=30, second=0, microsecond=0)
delta = end_time - start_time
time.sleep(delta.total_seconds())
# do stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM