pythonfunctiontype-conversionminute

Why is function within main function in python always returning "none" when it should return a float?


In order to learn python, I am trying to take a string from the user, convert this string in a float. I need to convert the minutes in a decimal number. This is what the "convert" function intends to do.

But I always get "none" as output. What is wrong?

   def main():
    
     time = input("what time is it?")
    
     def convert (a):

   #this split the string 

        x, z = time.split(":")
        x = float(x)
        z = float(z)

  #converts hours and minutes to float

        if z > 0:
           z = z / 60

  #converts minutes to decimals

        else:
          z = 0
          k = x + z
          return k
    
     result = convert(time)
     print(result)
    
    if __name__ == "__main__":
        main()

Ok so when reviewing the whole thing, and using this code as follows, I have the error "expected an intended block after function definition on line 1". This indentation stuff seems not easy.

def main():

time = input("what time is it?")

def convert (a):
    x, z = time.split(":")
    x = float(x)
    z = float(z)
    return x * (z / 60)
    

result = convert(time)
print(result)

if __name__ == "__main__":
    main()

Ok so now it finally works...after I placed a small indentation after the first "main" line, like so:

def main():

 time = input("what time is it?")

 def convert (a):
    x, z = time.split(":")
    x = float(x)
    z = float(z)
    return x * (z / 60)


 result = convert(time)
 print(result)

if __name__ == "__main__":
    main()

Solution

  • There are code paths in your function that do not reach the return statement. As per the Python semantics, when this happens, None is returned implicitly. Concretely, this happens when z>0. I assume you would want to fix the indentation of the return statement in the else branch. Looking at what you were trying to do, that seems like it would result in the correct behaviour. There is also a way to simplify your code, if you assume that inputs like "20:-10" would not occur, because that's the only way

    def main():
    
        time = input("what time is it?")
      
        def convert (a):
    
           #this split the string 
    
           x, z = time.split(":")
           x = float(x)
           z = float(z)
    
           return x + z / 60
    
        result = convert(time)
        print(result)
    
    if __name__ == "__main__":
        main()