jeudi 5 décembre 2019

Function not returning converted type of variable

I have an assignment and have created a function called cycle_convert(variable, n) that converts the type of a variable based upon the number of step sizes n. I have the following fixed order of types in Python: int → float → bool → string → complex

For example I have the variable number = 10 and with my function cycle_convert(number, 2) it would change the type from a int to a bool. It also works for wrapping round and negative step sizes.

I have code that completes these tasks but when returning the variable, even though the function converts it, the converted type does not seem to return and variable number is still an int. My code is as follows:

def cycle_convert(x, n=1):
    if type(x) == int:
        num = 1
    elif type(x) == float:
        num = 2
    elif type(x) == bool:
        num = 3
    elif type(x) == str:
        num = 4
    elif type(x) == complex:
        num = 5
    prev_type = type(x)

    final_num = num + n
    while final_num not in range(1,6):
        if final_num <1:
            final_num = 5 + final_num
        if final_num >5:
            final_num = final_num - 5

    if final_num == 1:
        x = int(x)
    elif final_num == 2:
        x = float(x)
    elif final_num == 3:
        x = bool(x)
    elif final_num == 4:
        x = str(x)
    elif final_num == 5:
        x = complex(x)
    print('Your variable type has been changed from ', prev_type, 'to ', type(x), ': ')
    return x


number = 10
cycle_convert(number, 2)

Can anyone explain to me why the return function does not work in this instance?

Thanks

Aucun commentaire:

Enregistrer un commentaire