Home > Mobile >  Find smaller number from 2 provided - works, but throws an error. TypeError: cannot unpack non-itera
Find smaller number from 2 provided - works, but throws an error. TypeError: cannot unpack non-itera

Time:01-05

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()

CodePudding user response:

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.

CodePudding user response:

  • Your function returns nothing, you can modify it to return number, which is the smaller number found betwwen x and y
  • You try to catch two values x and y (a tuple) from a function which returns nothing/None, so it does not works porperly
  • It is better to get the returned value, and print the answer in the main() part of the code.

Code:

def smaller_num(x, y):
    if x > y:
        number = y
    else:
        number = x
    return number

def main():
    x=int(input('Enter first number: '))
    y=int(input('Enter second number: '))
    number = smaller_num(x, y)
    print(f'Smaller number, between {x} and {y} is {number}')

if __name__ == '__main__':
    main()

CodePudding user response:

Small things: Your main x, y was calling your function for both. Main calling loop had syntax mistake.

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

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

if __name__ == '__main__': 
    main()
  •  Tags:  
  • Related