Skip to content
Advertisement

Python converting sec to min with while and if

minutes = 0
def sec_to_min():
    seconds = int(input("How many seconds you want to convert?"))
    while True:
        if seconds >= 60:
            seconds =-60
            minutes =+1
            print(minutes)
            return True
        else:
            print(seconds,"sec")
            return False

sec_to_min()

When I input 60 or more, it will print just “1”, nothing more. My if is not working. I tried to move “seconds” in front of function but it gave me an error, something like “local variable ‘seconds’ referenced before assignment”

Advertisement

Answer

I’ll summarize:

We think you’ve confused two types of statements:

seconds = -60
seconds -= 60

The first one deletes the previous value of seconds and assigns a new value of -60; the second is equivalent to

seconds = seconds - 60

The flow of your code suggests that this second one is what you need; the same change applies to minutes.

You have a conflict in your while logic: although the loop control seems to want to repeat the loop for a while, it gets interrupted during the first iteration by one return statement or the other. You have no way to reach the bottom of the loop and go back for a second iteration.

Why are you returning a Boolean value? That’s not clear, since your main code doesn’t use it. If you do require the return value, perhaps you need to set a variable within the loop, and then return that variable after the loop.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement