I can get the Fahrenheit to Celcius side working but not the other way around
# converts between C and F
# conversion = C * 9/5 +32 = F
unit = input("is the temperature in Celsius or Fahrenheit (C/F): ")
temp = float(input("Enter the temperature: "))
while unit != ("F" or "C"):
unit = input("""Please enter the unit of temperature, Celsius or Fahrenheit (C/F): """)
if unit == "C":
c_temp = (temp * 9/5) +32
print (c_temp)
elif unit == "F":
c_temp = (temp - 32) / (9/5)
print(c_temp)`
` whenever I run it, it seems to accept the F but never the C and just keeps asking the same promt constantly. i've tried changing the operators and eventually added brackets arounds the while loop which worked for the first one but not the second one in the line, i tried experimenting with true and false but i got completely and utterly lost that i gave up on that lol
i'm so confused man`
The issue lies in the condition inside your while loop. The condition:
while unit != ("F" or "C"):
does not behave as expected. This is because ("F" or "C") evaluates to "F" (since non-empty strings are truthy, and "F" is the first operand). So, the condition effectively becomes:
while unit != "F":
This causes the loop to behave incorrectly. Instead, you should use:
while unit not in ("F", "C"):
Here is the corrected code:
# Converts between Celsius and Fahrenheit
# Conversion formula: C * 9/5 + 32 = F
unit = input("Is the temperature in Celsius or Fahrenheit (C/F): ").strip().upper()
# Loop to ensure valid input for the unit
while unit not in ("F", "C"):
unit = input("Please enter the unit of temperature, Celsius or Fahrenheit (C/F): ").strip().upper()
temp = float(input("Enter the temperature: "))
# Perform the conversion
if unit == "C":
f_temp = (temp * 9/5) + 32
print(f"The temperature in Fahrenheit is: {f_temp:.2f}°F")
elif unit == "F":
c_temp = (temp - 32) / (9/5)
print(f"The temperature in Celsius is: {c_temp:.2f}°C")
Corrected while condition, unit not in ("F", "C") ensures valid input. strip() and upper(), Cleans up user input by removing extra spaces and converting it to uppercase to avoid case sensitivity issues.
Added formatted output for better readability. Now, it should work correctly for both Celsius to Fahrenheit and Fahrenheit to Celsius conversions.