Python beginner Diary Day 010: Weight Conversion

I followed a chapter of Bro Code’s full Python course about creating a weight converter with Python. It converts kilograms into pounds or vice versa. For me, it was interesting to see how this is done using if-statements and made use of some f-strings.

One of my personal favorite things was that I figured out a way to allow user input to be case-insensitive, so no matter if they would put in a lowercase K or uppercase K, or lowercase L or uppercase L, it will automatically convert it into the right way, which is uppercase for the script, so that the user would not have to think about it.

Here’s the code:

# Python weight converter

weight = float(input("Enter your weight: "))
unit = input("Kilograms or Pounds? (K or L): ").upper()

if unit == "K":
    weight = weight * 2.205
    unit = "Lbs."
    print(f"Your weight is: {round(weight, 1)} {unit}")
elif unit == "L":
    weight = weight / 2.205
    unit = "Kg."
    print(f"Your weight is: {round(weight, 1)} {unit}")
else:
    print(f"{unit} is not a valid unit")

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *