Python except ValueError: 当为真时

问题描述 投票:0回答:1

我试图使用 "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()
python while-loop valueerror except
1个回答
1
投票

positive_int() 函数不返回任何内容,这意味着 num = positive_int() 套餐 numNone. 后来,当它试图添加这个代码时,代码失败了。None 值为一个int。

你可以通过以下两种方式来解决这个问题 break 语句,或者通过返回 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

0
投票

你既用factorial作为函数名,又用变量名。


0
投票

问题是 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()
© www.soinside.com 2019 - 2024. All rights reserved.