Sam Scolari
Sam Scolari

Reputation: 52

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.

Upvotes: 0

Views: 403

Answers (2)

user8651755
user8651755

Reputation:

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

Upvotes: 0

spalac24
spalac24

Reputation: 1116

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.

Upvotes: 1

Related Questions