Python Forum

Full Version: unpacking tuple not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I'm creating a simple calculator. I'm having trouble with unpacking a tuple. My IDE returns an error saying,
Quote:(num1, num2, den1, den2) = numbers #unpacking does NOT work
ValueError: not enough values to unpack (expected 4, got 0)

This appears to occur from line 22. I have more to do after, but this is holding me up.

The odd thing is that when I print the vars on lines 25-28, they appear to have been (re)assigned the tuple's correct values. Lines 39-41 similarly work, except they aren't returned as a tuple in line 51 as I expected.

Any ideas what I'm doing wrong?


"""
Takes in 2 fractions, and performs various operations on it:
- add
- subtract
- multiply
- divide
- Then simplify the fraction for its final form
"""

"""Get integers from user"""
def input_nums():
        num1 = int(input('enter num1: '))
        num2 = int(input('enter num2: '))
        den1 = int(input('enter denominator1: '))
        den2 = int(input('enter denominator2: '))
        return (num1, num2, den1, den2)  # returns vars in tuple

def mixed_fraction(*numbers): # unpack tuple
    print(numbers)
    print("length of tuple 'numbers' = ", len(numbers)) # correctly shows 4 elements

    (num1, num2, den1, den2) = numbers #unpacking does NOT work

    # but here, these work, as they received indexes, eg. num1 = numbers[0]
    print("num1 = ", num1)
    print("num2 = ", num2)
    print("den1 = ", den1)
    print("den2 = ", den2)


    #get common denominator
    common_den = den1 * den2     # numbers[2] * numbers[3]
    
    #cross multiply
    numA = num1 * den2   # numbers[0] * numbers[3]
    numB = num2 * den1   # numbers[1] * numbers[2]

    # test to make sure the vars are assigned correctly
    print("numA = ", numA)
    print("numB = ", numB)
    print("common_den = ", common_den)

    return (numA, numB, common_den)     # returns vars in tuple


numbers = input_nums() # tuple 'numbers' stores vars num1, num2 as numbers[0] and number[1]
mixed_fraction(*numbers) # pass tuple 'numbers' into function via unpacking. Cleaner than passing entire tuple 'numbers' directly


# next 2 lines currently NOT working, as no values are being returned here
mixed_vars = mixed_fraction()
print(mixed_vars)
on line 51 mixed_vars = mixed_fraction() you call mixed_fraction() without any argument, thus numbers argument is empty tuple.
you don't need line 47 - you call the function and then throw away the return values.

So I guess you want to replace lines 47 and 51 with mixed_vars = mixed_fraction(*numbers)

numbers = input_nums() # tuple 'numbers' stores vars num1, num2 as numbers[0] and number[1]
mixed_vars = mixed_fraction(*numbers)
print(mixed_vars)