不支持的操作数类型+:' NoneType'和' int'

时间:2016-05-11 21:46:45

标签: python python-3.x types

我目前的代码是这样做的:"打印从零到给定最大值的所有完美正方形。该版本经过重构,使其更易于理解和更易于维护。"

目前我的问题是关于这段代码:

def read_bound(prompt):
   """Reads the upper bound from the standard input (keyboard).
      If the user enters something that is not a positive integer
      the function issues an error message and retries
      repeatedly"""
   upper_bound = None
   while upper_bound is None:
       line = input(prompt)
       if line.isnumeric():
           return int(line)
       else:
           print("You must enter a positive number.") 

在调用主要功能时:

def main():
   """Bring everything together"""
   lower_bound = read_bound("Enter the lower bound: ")
   upper_bound = read_bound("Enter the upper bound: ")
   squares = []
   for num in range(lower_bound, upper_bound + 1):
       if is_perfect_square(num):
           squares.append(num)

   print_squares(lower_bound, upper_bound, squares)

我收到错误:

builtins.TypeError:+:' NoneType'不支持的操作数类型和' int'

为什么用户提供的第一个对象属于' none'但第二个是' int'。我希望他们都是整数。我做错了什么?

两个答案都是相同的,并解决了我的问题。因此,我对问题中的代码进行了修改。谢谢!

2 个答案:

答案 0 :(得分:2)

函数read_bound不包含return语句。如果执行在Python中到达函数的末尾,the function will return None,那么upper_bound将为None

目前您已分配给一个本地变量,该变量恰巧与upper_bound中的main共享该名称,但由于您从未阅读该名称,因此该变量无效。

修改read_bound以包含退货:

def read_bound(prompt):
    """Reads the upper bound from the standard input (keyboard).
       If the user enters something that is not a positive integer
       the function issues an error message and retries
       repeatedly"""
    upper_bound = None
    while upper_bound is None:
        line = input(prompt)
        if line.isnumeric():
            return int(line)  # <-- added
        else:
            print("You must enter a positive number.") 

答案 1 :(得分:2)

读取绑定代码未返回输入

def read_bound(prompt):
"""Reads the upper bound from the standard input (keyboard).
   If the user enters something that is not a positive integer
   the function issues an error message and retries
   repeatedly"""
 upper_bound = None
 while upper_bound is None:
    line = input(prompt)
    if line.isnumeric():
        return int(line)
    else:
        print("You must enter a positive number.")