Is there another way to write my if else stament?

Viewed 37

I am brand new to python and I am trying to make a little unit conversion program.

So here is a portion of my code.

choicek = int(input(f"Enter Kilograms: ") if choice == "1" else exit)

Kilorate = 2.2046

answerK = choicek *Kilorate

print(round(answerK, 2))

choicep = int(input(f"Enter Pounds: ") if choice == "2" else exit)

Poundrate = 2.2046

answerP = choicep/Poundrate

print(round(answerP, 2))


choicel = int(input(f"Enter Liters: ") if choice == "3" else exit)

Literrate = 3.785412

answerL = choicel/Literrate

print(round(answerL, 2))


choiceg = int(input(f"Enters Gallons: ") if choice == "4" else exit)

Gallonrate = 3.785412

answerG = choiceg * Gallonrate

print(round(answerG, 2))

Sorry for that mess, anyways. The problem I am having is that if I do not input 1, then the program exits. I understand that it is this way because I am telling it "If 1 is not typed in, then exit the program". But I want it to be so that I can put 1 or 2 or 3 or 4.

Is there another way I can write this without having to put exit at the end of the If statement? Any advice would be appreciated, and again I am very new to this.

2 Answers

Regardless of choice, you execute essentially the same code. The only real differences are the input prompt and the conversion rate. So let's factor those out.

Also, it's better not to use the round function when your goal is to print two significant decimal digits, for reasons explained elsewhere. Instead, tell the print function to do the rounding using the .2f format.

# Unit conversions from NIST Special Publication 811, Appendix B.8
# https://www.nist.gov/pml/special-publication-811/nist-guide-si-appendix-b-conversion-factors/nist-guide-si-appendix-b8

if choice == 1:
    unitsIn = 'kilograms'
    rate = 1 / 0.4535924
elif choice == 2:
    unitsIn = 'pounds'
    rate = 0.4535924
elif choice == 3:
    unitsIn = 'liters'
    rate = 1 / 3.785412
elif choice == 4:
    unitsIn = 'gallons'
    rate = 3.785412
else:
    import sys
    print('unknown conversion requested', file=sys.stderr)
    sys.exit(1)

quantityIn = float(input(f'Enter {unitsIn}: '))
quantityOut = quantityIn * rate
print(f'{quantityOut:.2f}')

Use a smart data-structure, so your code can be simple and stupid:

conversion = {
    1: ("Kilograms", 2.2046),
    2: ("Pounds", 1/2.2046),
    3: ("Liters", 1/3.785412),
    4: ("Gallons", 3.785412)
}

if choice not in conversion.keys():
    print(f"Invalid choice: {choice}, should be 1-4.")
    sys.exit()

unitin, factor = conversion[choice]
numin = float(input(f"Enter {unitin}:"))
print(round(numin*factor, 2))

Related