Search code examples
pythonfunctionnumberstypeerroriterable

Find smaller number from 2 provided - works, but throws an error. TypeError: cannot unpack non-iterable NoneType object


I am getting into python again, and I don't get why it gives me an error, while working perfectly fine.

def smaller_num(x, y):
    if x > y:
        number = y
    else:
        number = x
print(f'Smaller number, between {x} and {y} is {number}')

def main():
    x, y = smaller_num(x=int(input('Enter first number: ')), y=int(input('Enter second number: ')))
    smaller_num(x, y)


if __name__ == '__main__':
    main()

Solution

  • This is because you are trying to assign values to x and y from function that doesn't return anything but only prints the result. i.e. function named smaller_num

    def main(): 
        x=int(input('Enter first number: '))
        y=int(input('Enter second number: '))
        smaller_num(x, y)
    

    This could be one solution to the problem. Notice that here x and y here are assigned from input and then prints smaller number. Also if you really want to do it in one line then:

    def main(): 
        smaller_num(int(input('Enter first number: ')), int(input('Enter second number: ')))
    

    This would work fine. You just need to modify main function to any of these.