Python except ValueError: While True

Python except ValueError: While True

我正在尝试使用 'while true' 要求用户输入 0 或正整数。我尝试了几种不同的方法,但它们似乎都有不同的问题。函数 def positive_int 拒绝字母和负整数,但不允许阶乘函数工作。阶乘函数独立运行。我得到一个错误代码:TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' for this line for i in range(1,num + 1):.谢谢您的帮助。

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

您正在使用阶乘作为函数名和变量名。

问题是 positive_int 没有返回任何东西

尝试:

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

positive_int() 函数没有 return 任何东西,这意味着 num = positive_int()num 设置为 None。代码后来在尝试将此 None 值添加到 int.

时失败

您可以通过将 break 语句替换为 return 或在跳出循环后 returning num 来解决此问题:

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.") 

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