简体   繁体   中英

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()

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

You are using factorial both as a function name and as a variable name.

Problem is positive_int is not returning anything

Try:

def positive_int(prompt=''):
     while True:
         try:
             num = int(input(prompt))
             if num < 0:
                 raise ValueError

             return num  # change to return value rather than 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM