Search code examples
pythonwhile-loopvalueerrorexcept

Python except ValueError: While True


I'm trying to use 'while true' to ask the user to input 0 or a positive integer. I've tried a couple different ways and they all seem to have different issue. The function def positive_int rejects the letters and negative ints but will not allow the factorial function to work. The factorial function works on its own. I get an error code: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' for this line for i in range(1,num + 1):. Thanks for the help.

def positive_int(prompt=''):
     while True:
         try:
             num = int(input(prompt))
             if num < 0:
                 raise ValueError
             break
         except ValueError:
             print("Please enter a positive integer.")     

print('\n')    
print("The program will compute and output the factorial number.")
def factorial():
        num = positive_int('Please enter the number to factorial: ')
        factorial = 1
        if num == 0:
           print("\nThe factorial of 0 is 1")
        else:
           for i in range(1,num + 1):
               factorial = factorial*i
           print("\nThe factorial of", num,"is",factorial)  
factorial()

Solution

  • The positive_int() function doesn't return anything, which means that num = positive_int() sets num to None. The code later fails when it tries to add this None value to an int.

    You can fix this by either replacing the break statement with a return, or by returning num after breaking out of the loop:

    def positive_int(prompt=''):
         while True:
             try:
                 num = int(input(prompt))
                 if num < 0:
                     raise ValueError
                 return num  # Replacing break with return statement 
             except ValueError:
                 print("Please enter a positive integer.") 
    

    or

    def positive_int(prompt=''):
         while True:
             try:
                 num = int(input(prompt))
                 if num < 0:
                     raise ValueError
                 break
             except ValueError:
                 print("Please enter a positive integer.") 
    
         return num  # Breaking out of the loop takes you here