File size: 1,317 Bytes
2cf52e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import streamlit as st

def main():
    st.title("Temperature Converter")
    st.write("Convert temperatures between Celsius, Fahrenheit, and Kelvin.")

    # Input fields
    temperature = st.number_input("Enter the temperature to convert", value=0.0)
    from_unit = st.selectbox("From Unit", ["Celsius", "Fahrenheit", "Kelvin"])
    to_unit = st.selectbox("To Unit", ["Celsius", "Fahrenheit", "Kelvin"])

    # Perform conversion
    if st.button("Convert"):
        try:
            converted_temperature = convert_temperature(temperature, from_unit, to_unit)
            st.success(f"{temperature} {from_unit} = {converted_temperature:.2f} {to_unit}")
        except ValueError as e:
            st.error(e)

def convert_temperature(value, from_unit, to_unit):
    """Converts temperature between Celsius, Fahrenheit, and Kelvin."""
    if from_unit == to_unit:
        return value

    # Convert to Celsius first
    if from_unit == "Fahrenheit":
        value = (value - 32) * 5 / 9
    elif from_unit == "Kelvin":
        value = value - 273.15

    # Convert from Celsius to target unit
    if to_unit == "Fahrenheit":
        return value * 9 / 5 + 32
    elif to_unit == "Kelvin":
        return value + 273.15
    else:  # to_unit == "Celsius"
        return value

if __name__ == "__main__":
    main()