7
\$\begingroup\$

The goal of this program is to convert the given weight of the user LBS or KG into the opposite of what they used ex: 180lbs will convert to kg

Weight = float(input("Enter your weight: "))
Weight_Metric = input("Type L/l for LBS and K/k for KG: ")

if Weight_Metric == "L" or Weight_Metric == "l":
    lbs_to_kg = (float(Weight * 0.453592))
    #Note that the conversion of lbs to kg might not be exact
    print(f'If you are {Weight} in pounds then you are AROUND {lbs_to_kg} in KG')
elif Weight_Metric == "K" or Weight_Metric == "k":
    kg_to_lbs = (float(Weight * 2.205))
    #Note that the conversion of kg to lbs might not be exact
    print(f"If you are {Weight} in kilograms then you are AROUND {kg_to_lbs} in LBS")

I'm very new to python and coding in general, so I'm doing mini projects that combine things I've learned and this is was my first one, and I just wanted to know if there was something that I did wrong and could ruin the entire program.

\$\endgroup\$

2 Answers 2

10
\$\begingroup\$

In this review I'll focus on a few habits you should cultivate if you want to become proficient in programming.

Learn the Python naming conventions. For example, lowercase for variable and function names, UPPERCASE for constants, and CamelCase for classes.

Use functions for all of your code. At the top level of your script, there should be nothing happening other than imports, constants, and function (or class) definitions. Adopt that discipline from the outset and your learning will progress faster.

Embrace command-line arguments. The most successful and ubiquitous scripts/commands in computing history (think of the typical commands in a Unix shell, or their analogues in Windows) do not engage in tedious dialogues with their users. Instead, they take their inputs directly from command line arguments, do something, and then exit -- that's it. That model has been so successful because it allows different commands to be combined in various ways (for example, the output of one command piped directly as input into another) and for the commands to operate successfully without any human intervention at all. You may not appreciate all of those benefits yet, but if you continue with programming, your appreciation will grow. The way to start is to design your programs so that they run primarily from command-line arguments (sys.argv in the example below). I left input() in the program simply to be faithful to your original code, but in my own programs I (almost) never use it.

If you must use input() don't do it more than necessary. Python can easily parse inputs like "75 kg". No need to extend the computer dialogue into separate questions.

Build programs by combining the behaviors of small, well-focused functions. In the example below, we have a function to get the weight from the command-line arguments (or from user input) and another function to convert the weight.

Use data structures to simplify logic and improve code readability. In the example, the conversion is driven entirely by data that is easy to understand.

Keep messages to users brief and to-the-point. If you can rewrite a message in a more compact way, do it. Less verbose, less chatty messages are easier to maintain in your code and they are less of a cognitive burden on users.

Next steps: add validation to the input handling. If the user provides invalid inputs, get_weight() or convert() will fail. But you can easily fix that. There are multiple examples on CodeReview (I have written a couple) illustrating how to build a general-purpose function to get user input, convert it, and validate it.

import sys

CONVERSIONS = {
    'lb': (0.453592, 'kg'),
    'kg': (2.205, 'lb'),
}

def main(args):
    weight, unit = get_weight(args)
    converted, new_unit = convert(weight, unit)
    print(f'That equals {converted} {new_unit}.')

def get_weight(args):
    if args:
        weight, unit = args
    else:
        prompt = 'Enter your weight and its units (lb or kg): '
        reply = input(prompt)
        weight, unit = reply.strip().lower().split()
    return (float(weight), unit)

def convert(weight, unit):
    factor, new_unit = CONVERSIONS[unit]
    return (round(weight * factor, 2), new_unit)

if __name__ == '__main__':
    main(sys.argv[1:])

\$\endgroup\$
3
\$\begingroup\$

There's nothing wrong here. But it will take some practice to craft more mature code.


The whole thing is at __main__ top-level. Consider def convert(): so you define a units conversion function.

Or better, def convert(weight: str):, and pip install typer to make it easy to invoke from the command line:

import typer

def convert(weight: str):
    ...

if __name__ == "__main__":
    typer.run(convert)

Try it out with a command line argument of --help, for example.


Weight = float(input("Enter your weight: "))

Pep-8 asks that you spell it lowercase weight. We expect that capitalized Weight would instead represent a class.


if Weight_Metric == "L" or Weight_Metric == "l":

This works. DRY. Consider re-phrasing it as if weight_metric.upper() == "L":

Sometimes we need this idiom instead: if y_or_n in ("y", "n"):


    lbs_to_kg = (float(Weight * 0.453592))

You already went to the trouble of converting str to float for that weight. No need to do it again. It's harmless to talk about float(float(float(1))), but it won't do any additional good.


    kg_to_lbs = (float(Weight * 2.205))

This is the same number we saw above, just in reciprocal form.

Conversion factors, which have a value of 1.0, are a powerful technique. Consider doing a pip install of unyt or similar package which offers that abstraction.

\$\endgroup\$
1
  • \$\begingroup\$ I'm trying to understand majority of what I'm reading, but some of it is a bit more than I can handle, but something I've seen consistently is that I should be using functions instead of what I was doing with all the variables, as well as learning the naming conventions for Python. Your notes are appreciated and I'll consider them going forward, thank you. \$\endgroup\$
    – Uncharted
    Commented Mar 2, 2023 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.