rafay2301/Unitconversion136
0
1import streamlit as st2 3# Conversion functions4def convert_mass(value, from_unit, to_unit):5 units = {"kg": 1, "g": 1000, "lb": 2.20462, "oz": 35.274}6 return value * (units[to_unit] / units[from_unit])7 8def convert_length(value, from_unit, to_unit):9 units = {"m": 1, "cm": 100, "mm": 1000, "inch": 39.3701, "ft": 3.28084}10 return value * (units[to_unit] / units[from_unit])11 12def convert_temperature(value, from_unit, to_unit):13 if from_unit == to_unit:14 return value15 elif from_unit == "C" and to_unit == "F":16 return (value * 9/5) + 3217 elif from_unit == "F" and to_unit == "C":18 return (value - 32) * 5/919 elif from_unit == "C" and to_unit == "K":20 return value + 273.1521 elif from_unit == "K" and to_unit == "C":22 return value - 273.1523 elif from_unit == "F" and to_unit == "K":24 return (value - 32) * 5/9 + 273.1525 elif from_unit == "K" and to_unit == "F":26 return (value - 273.15) * 9/5 + 3227 28def convert_pressure(value, from_unit, to_unit):29 units = {"Pa": 1, "kPa": 0.001, "bar": 1e-5, "psi": 0.000145038}30 return value * (units[to_unit] / units[from_unit])31 32def convert_energy(value, from_unit, to_unit):33 units = {"J": 1, "kJ": 0.001, "cal": 0.239006, "kcal": 0.000239006}34 return value * (units[to_unit] / units[from_unit])35 36# Streamlit UI37st.title("Unit Converter")38 39category = st.selectbox("Choose a category", ["Mass", "Length", "Temperature", "Pressure", "Energy"])40 41if category == "Mass":42 units = ["kg", "g", "lb", "oz"]43elif category == "Length":44 units = ["m", "cm", "mm", "inch", "ft"]45elif category == "Temperature":46 units = ["C", "F", "K"]47elif category == "Pressure":48 units = ["Pa", "kPa", "bar", "psi"]49elif category == "Energy":50 units = ["J", "kJ", "cal", "kcal"]51 52value = st.number_input("Enter value", min_value=0.0, format="%.5f")53from_unit = st.selectbox("From", units)54to_unit = st.selectbox("To", units)55 56if st.button("Convert"):57 if category == "Mass":58 result = convert_mass(value, from_unit, to_unit)59 elif category == "Length":60 result = convert_length(value, from_unit, to_unit)61 elif category == "Temperature":62 result = convert_temperature(value, from_unit, to_unit)63 elif category == "Pressure":64 result = convert_pressure(value, from_unit, to_unit)65 elif category == "Energy":66 result = convert_energy(value, from_unit, to_unit)67 68 st.success(f"Converted Value: {result:.5f} {to_unit}")