Hi everyone. I spent a lot of time figuring out how to get my code to check for user errors and types. I finally got it set up properly, but now I'm getting an error.

A number is required on my input. If someone doesn't enter a number or leaves the input blank, it tells them to enter a number and gives them the input again.

If the user enters a number the first time, the code executes properly.
If the user makes a mistake, but enters a number the next time around (after it told them to enter a number and gave them the input again), it gives an error.

This is my code:

def kcinput():
  try:
    kcelv = float(input("\nWhat is the degrees in Celsius? "))
    return kcelv
  except SyntaxError:
    print ("You must enter a number!")
    kcinput()
  except NameError:
    print ("You must enter a number!")
    kcinput()
  except:
    print ("You must enter a number!")
    kcinput()
kcel = kcinput()
print ("")
print (kcel, "degrees Celsius is", kcel + 273, "degrees Kelvin.\n\n")

And this is the error the user will get:

Traceback (most recent call last):
  File "convert.py", line 67, in <module>
    convert()
  File "convert.py", line 35, in convert
    print (kcel, "degrees Celsius is", kcel + 273, "degrees Kelvin.\n\n")
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

So apparently after the user makes a mistake and the function is re-run, the variable does not get assigned to the input the way it does the very first time the function is run.

This is a really strange situation to me, and I have no idea what's going on.

Thank you to anyone who replies!

The problem is that you call kcinput() instead of return kcinput(). Use a loop for such problems instead of recursion

from __future__ import print_function
import sys
if sys.version_info < (3,):
    input = raw_input
# these lines were for python before 3.0

def kcinput():
    for i in range(2):
        try:
            return float(input("\nWhat is the degrees in Celsius? "))
        except Exception:
            if i:
                raise
            else:
                print("You must enter a number!")

if __name__ == "__main__":
    print(kcinput())

Wow, all I had to do was return the function on the exceptions instead of calling it. I don't know why, but that just didn't click. Thank you so much for your reply, it works perfectly now!

Wow, all I had to do was return the function on the exceptions instead of calling it. I don't know why, but that just didn't click. Thank you so much for your reply, it works perfectly now!

A high percentage of errors involving None come from forgotten return :)

commented: sweet and simple +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.