-1

I was creating an if-else loop based on the type of variable, to either convert a list of numbers to kilograms, or simply one number, and for some reason I cannot call the variable I created into my main() function. I am a beginner to python and any help would be appreciated. Here is my code:

# Testing Code

def kgToLb(weight):
    # Return the converted weight (kg)
    newWeight = []
    if type(weight) == list:
        for w in range(len(weight)):
            return newWeight.append(weight[w] * 2.20462)
    return newWeight == weight * 2.20462



def main():
    weightList = [-22, 11, 0, 8.2, -8.2]
    answerKgsList = [-9.979044, 4.989522, 0, 3.71946186, -3.71946186]
    # Test data

    for w in range(0, len(weightList)):
        kgToLb(weightList)
        correctWeight = weightList == answerKgsList[w]
        print(correctWeight)
        print(newWeight)
        print("The converted weight is " + str(newWeight[w]) + ". " + str(correctWeight))


main()

I tried to change the if-else format to see if it would change anything to no avail.

anon
  • 3
  • 2
  • Welcome to Stackoverflow! Right off the back running your code causes some variable-not-defined errors. Could you please check that your example is in order? – Steinn Hauser Magnússon Nov 15 '22 at 16:12
  • 1
    You don't assign the return value of your function `kgToLb` into a variable, so that value is lost. You're trying to use `newWeight` in `main` but it is not defined there. – kindall Nov 15 '22 at 16:12
  • What do you expect `kgToLb` to do? – EDG956 Nov 15 '22 at 16:14
  • 1) you're not doing anything with the return value of `kgToLb` function here: `kgToLb(weightList)`. 2) `newWeight.append` returns `None`, if you want to return the updated list you need to first call `newWeight.append(...)` and then `return newWeight`. 3) `newWeight == weight * 2.20462` the `==` is a logical comparison so this returns a boolean value, again you want to separately `newWeight = weight * 2.20462` (single `=`) and then `return newWeight` – Anentropic Nov 15 '22 at 16:15
  • 1. `if-else` is not a loop. 2. [Don't use `type(...) == ...` to check for the type of objects](https://stackoverflow.com/a/154156/843953). 3. Do you understand what `==` means? Wha do you expect `newWeight == weight * 2.20462` to do? 4. _"for some reason I cannot ..."_ What happens when you do this? Does your code throw an error? Does it fail silently? Does it give you an unexpected answer? Please take the [tour], and read [what's on-topic here](/help/on-topic), [ask], and the [question checklist](//meta.stackoverflow.com/q/260648/843953). Welcome to Stack Overflow! – Pranav Hosangadi Nov 15 '22 at 16:16
  • `kgToLb` should make a *single* conversion. If you have a list of weights to convert, just use a list compression like `[kgToLb(w) for w in weights]`. Don't make the conversion function responsible for telling the difference between one and many weights. – chepner Nov 15 '22 at 16:17

2 Answers2

0

You're very close! Here's a working solution:

def kgToLb(weight):
    # Return the converted weight (kg)
    newWeight = []
    if type(weight) == list:
        for w in range(len(weight)):
            newWeight.append(weight[w] / 2.20462) # fix "return" and that you multiply. Should divide
    return newWeight # just return the new list

def main():
    weightList = [-22, 11, 0, 8.2, -8.2]
    answerKgsList = [-9.979044, 4.989522, 0, 3.71946186, -3.71946186]
    # Test data

    newWeight = kgToLb(weightList) # save return of function to variable

    tolerance = 0.001 
    # when comparing two floats, always use some tolerance for when 
    # to consider them "equal.". If abs(A-B) < tol, then they're equal

    for w in range(0, len(weightList)):
        correctWeight = abs(newWeight[w] - answerKgsList[w]) < tolerance
        print("The converted weight is " + str(newWeight[w]) + ". " + str(correctWeight))

main()
# >>> The converted weight is -9.979044007584074. True
# >>> The converted weight is 4.989522003792037. True
# >>> The converted weight is 0.0. True
# >>> The converted weight is 3.7194618573722456. True
# >>> The converted weight is -3.7194618573722456. True

Mainly the issue was that you used the return argument when you did the append() operation. This operation returns None so your function gets a bit messed up there. You were also multiplying by the conversion value instead of dividing. Also, when you're comparing two float values in python, you need a "tolerance" level for when you consider the two values equal. I.e. 0.030000001 will not be equal to 0.03 in python. I set your tolerance to 0.001 but you might want to change this depending on your level of precision. Have fun!

  • I appreciate the quick help. I was totally clueless to the fact that my function did not really do anything at first. I definitely would not have figured out the tolerance thing on my own. You made my day with this help comment! – anon Nov 15 '22 at 16:48
  • Thanks @Santi ! If this solved your issue you can mark it as the solution to close the thread. Glad I could help! – Steinn Hauser Magnússon Nov 15 '22 at 17:28
0

You are returning newWeight too soon. (Actually, you are incorrectly returning the None value that newWeight.append produces too soon.)

def kgToLb(weight):
    # Return the converted weight (kg)
    newWeight = []
    if type(weight) == list:
        for w in range(len(weight)):
            newWeight.append(weight[w] * 2.20462)
        return newWeight
    return weight * 2.20462

There are a few other problems with this function, but it's not worth going over them right now becauase this function is too complex to begin with. It should do one thing: convert a weight in kilograms to a weight in pounds.

def kgToLb(weight):
    return weight * 2.20462

A second function, if even needed, should use that to convert a list of weights.

def many_kgToLb(weights):
    return [kgToLb(w) for w in weights]

The caller knows if they have a single weight or a list of weights; let them pick the right function to call rather than making a single function make the decision.

chepner
  • 497,756
  • 71
  • 530
  • 681