【问题标题】:Python except ValueError: While TruePython 除了 ValueError: While True
【发布时间】:2020-08-10 12:28:49
【问题描述】:

我正在尝试使用“while true”来要求用户输入 0 或正整数。我尝试了几种不同的方法,但它们似乎都有不同的问题。函数 def positive_int 拒绝字母和负整数,但不允许阶乘函数工作。阶乘函数独立工作。我收到一个错误代码:TypeError:+ 的不支持的操作数类型:'NoneType' 和 'int' 对于这一行的 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()

【问题讨论】:

  • 让阶乘函数只有一个目的:计算阶乘,包括在参数非法时抛出异常。从提示中读取一个 int 应该通过从 main 调用 pisitive_int 来单独完成

标签: python while-loop valueerror except


【解决方案1】:

positive_int() 函数不返回任何内容,这意味着num = positive_int()num 设置为None。代码稍后在尝试将此 None 值添加到 int 时失败。

您可以通过将 break 语句替换为 return 或在跳出循环后返回 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

【讨论】:

    【解决方案2】:

    您将阶乘用作函数名和变量名。

    【讨论】:

      【解决方案3】:

      问题是 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()
      

      【讨论】:

        猜你喜欢
        • 2021-02-15
        • 1970-01-01
        • 2022-11-23
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-27
        • 2018-11-06
        相关资源
        最近更新 更多