1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I make a def function with my "if" statements?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    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: ")

    Continue reading...

Compartilhe esta Página