Hidden
Hidden

Reputation: 33

unsupported operand type(s) for +: 'NoneType' and 'int'

My current piece of code is made to do this: "Print all the perfect squares from zero up to a given maximum. This version is refactored to make it more understandable and more maintainable."

Currently my issue is in regards to this piece of code:

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

Upon calling the main function:

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)

I get the error:

builtins.TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Why is it that the first object given by the user is of the type 'none' but the second an 'int'. I wish for them to both be integers. What am I doing wrong?

Both answers given were identical and fixed my problem. Accordingly, my code in the question has been amended. Thanks!

Upvotes: 1

Views: 776

Answers (2)

galaxyan
galaxyan

Reputation: 6141

the read bound code did not return the input

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

Upvotes: 2

phihag
phihag

Reputation: 288270

The function read_bound does not include a return statement. If execution reaches the end of a function in Python, the function will return None, and thus upper_bound will be None.

Currently you assign to a local variable which coincidentally shares the name with the upper_bound in main, which will have no effect since you never read from it.

Modify read_bound to include a return:

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

Upvotes: 2

Related Questions