Right or wrong way to code?

So I have been following the “Python Full Course” (amazing!!
(Note: I’m only starting, currently at the project: Weight Converter)

The way I have written the code is:

weight = int(input("weight: "))
weight_type = input("(L)bs or (K)gs: ")
convert_to_kgs = weight / 2.2
convert_to_lbs = weight * 0.45
if weight_type == "l" or "L":
    print(convert_to_kgs)
else:
#weight_type == "k" or "K":
    print(convert_to_lbs)

Mosh’s Solution:

weight = int(input('weight: '))
unit = input('(L)bs or (K)gs: ')
if unit.upper() == 'L':
    converted = weight * 0.45
    print(f"You are {converted} kilos")
else:
    converted = weight / 0.45
    print(f"You are {converted} pounds")

whereas Mosh, has written it differently.
So the question is, should I be writing my code like Mosh or is it a case of if it works for you great and move on?

In his earlier lessons he explained that using “l” or “L”: is bad practice and you should always use .lower() or .upper(), and you are missing his print format “You are x pounds”, but your code does not have to be the same as other programmers to get to the correct answer.

1 Like

While there may not be a “right way” there are many “wrong ways” to write code. Many times the answer depends on the context. I expect that much of the code Mosh writes in his courses would be refactored before he would put it into a real project. That is because he has a different goal in writing the code that he does for these courses: instruction. Professional code would go through a code review process and be updated until both engineers were satisfied that it meets the standards for their project.

In this small code snippet, I would suggest that you should not do the conversion until you need it. Otherwise you will clutter your code with extra variables. It may also make sense to have the code that converts to pounds and kilos in helper functions.

Anyway, best of luck on your coding adventures!

2 Likes

I agree with everything @jmrunkle said. I would create a one function that just takes the weight and the unit, then the function should return the correct value.

If you haven’t came to the functions section of the course then the way you written it makes sense.

Also, Mosh is converting the input to upper so that you don’t have to write a compound conditional statement, looking for “l” and “L”. By the way, there should be an expression on both sides of the “or”.

if weight_type == "l" or weight_type == "L":
    print(foo)
else:
   print(bar)

In the way you have written it, try to replace if weight_type == 'l' or 'mary had a little lamb':
you will see what I mean.

1 Like