Home > OS >  How can I make a def function with my "if" statements?
How can I make a def function with my "if" statements?

Time:05-14

We were asked to make a function named temperature conversions that accepts an integer argument called temperature, a secondary string parameter called input unit, and a third string parameter called output unit. input unit specifies the unit of the value in temperature. This function shall convert and return the value in temperature to the unit specified in target unit. Both unit arguments shall be one of “C”, “K”, or “F”.

I came up with a bunch of if statements and it works, but I am not able to create the function that works.

input_unit, target_unit = input("Input the temperature and the unit to convert      it to: [e.g. 45c f > valid Units: C,K,F: ").split()
degree = int(input_unit[:-1])
i_unit = input_unit[-1].upper()
o_unit = target_unit.upper()

if i_unit == "C" and o_unit == "F":
  result = int((1.8 * degree)   32)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "C" and o_unit == "K":
  result = int(degree   273.15)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "K":
  result = int(((degree * 1.8)  32)  273.15)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "F" and o_unit == "C":
  result = int((degree  - 32) / 1.8)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "C":
  result = int(degree - 273.15)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
elif i_unit == "K" and o_unit == "F":
  result = int(((degree  - 273.15) - 32) / 1.8)
  print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
else:
  while True:
    input_unit, target_unit = input("Input the temperature and the unit to  convert it to?: ").split()
    if input_unit[-1].upper() != "C" or target_unit.upper() != "F":
      print("You enterd an invalid unit. Please enter again: ")

CodePudding user response:

Here I advise you to decompose your program in several steps first you ask for the temperature, then you make the conversion with a function and then you display the results.

def temperatureConversions(degree, i_unit, o_unit):
    if i_unit == "C" and o_unit == "F":
        return int((1.8 * degree)   32)
    elif i_unit == "C" and o_unit == "K":
        return int(degree   273.15)
    elif i_unit == "F" and o_unit == "K":
        return int(((degree * 1.8)  32)  273.15)
    elif i_unit == "F" and o_unit == "C":
        return int((degree  - 32) / 1.8)
    elif i_unit == "K" and o_unit == "C":
        return int(degree - 273.15)
    elif i_unit == "K" and o_unit == "F":
        return int(((degree  - 273.15) - 32) / 1.8)

valueCorrect = False
while(not valueCorrect):
    degree = input("Please enter a temperature (ex: 47C):\n")
    o_unit = input("Please enter the output unit desired(ex: C, F, K):")
    if(degree[:-1].isdigit()):
        i_unit, degree = degree[-1], int(degree[:-1])
        if(i_unit and o_unit in ['C', 'F', 'K']):
            valueCorrect = True
        else:
           print("Please write correct values of unit !") 
    else:
        print("Please write correct values of temperature !")

resultConversion = temperatureConversions(degree, i_unit, o_unit)

print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,resultConversion,o_unit))

Confirm me that it works for you.

CodePudding user response:

You can use this function

def convert(degree, i_unit, o_unit):
    if i_unit == "C" and o_unit == "F":
        result = int((1.8 * degree)   32)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    elif i_unit == "C" and o_unit == "K":
        result = int(degree   273.15)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    elif i_unit == "F" and o_unit == "K":
        result = int(((degree * 1.8)  32)  273.15)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    elif i_unit == "F" and o_unit == "C":
        result = int((degree  - 32) / 1.8)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    elif i_unit == "K" and o_unit == "C":
        result = int(degree - 273.15)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    elif i_unit == "K" and o_unit == "F":
        result = int(((degree  - 273.15) - 32) / 1.8)
        print("{:0.2f}°{} ⇒ {:0.2f}°{}".format(degree,i_unit,result,o_unit))
    else:
        while True:
            input_unit, target_unit = input("Input the temperature and the unit to  convert it to?: ").split()
            if input_unit[-1].upper() != "C" or target_unit.upper() != "F":
                print("You enterd an invalid unit. Please enter again: ")

CodePudding user response:

A much simpler approach would be to convert the input to a canonical unit (say, K) and then correspondingly convert to the desired output unit.

def c_to_k(degrees: float) -> float:
    return degrees   273.15

def k_to_c(degrees: float) -> float:
    return degrees - 273.15

def f_to_k(degrees: float) -> float:
    return degrees * 1.8   32   273.15

def k_to_f(degrees: float) -> float:
    return (degrees - 273.15 - 32) / 1.8

iconv = {
    "c": c_to_k,
    "f": f_to_k
}
oconv = {
    "c": k_to_c,
    "f": k_to_f
}

def temperature_conversion(
        temperature: float,
        input_unit: str,
        output_unit: str):
    input_unit = input_unit.lower()
    if input_unit != "k":
        temperature = iconv[input_unit](temperature)
    output_unit = output_unit.lower()
    if output_unit != "k":
        temperature = oconv[output_unit](temperature)
    return temperature

In very brief, the iconv and oconv dictionaries replace your if statements with a simple dictionary lookup which returns the function object to call for performing the canonical conversion.

Depending on your audience, you might want to add error checking to raise a more detailed exception than KeyError when an invalid unit is passed in.

If this seems too, er, sophisticated, a simpler implementation might avoid the dictionary lookup, and just use if statements to first convert the input to the canonical unit, then convert from that to the desired output unit. In this case the code can be simplified by changing the canonical unit to C, though:

if input_unit == "f":
    temperature = (temperature - 32) / 1.8
elif input_unit == "k":
    temperature -= 273.15
if output_unit == "k":
    temperature  = 273.15
elif output_unit == "f":
    temperature = temperature * 1.8   32

If you require high-precision results, you might want to avoid going through two separate calculations to convert between units, as the floating-point errors will compound and reduce the accuracy of the result. The complexities of your original code basically cannot be avoided in this case.(Perhaps see also Is floating point math broken? Converting Fahrenheit to Fahrenheit is somewhat likely to not return exactly the input number!) But your code which forced the floats to ints would obviously lose a lot more precision unnecessarily.

Notice how the function itself doesn't print anything, it just returns a number. A common design is to separate reusable functionality from user interface design, and so the responsibility to display the result to the user (or do whatever else that you want to do with it) falls on the caller.

  • Related