Home > Enterprise >  Program prints the else condition even when the if statements are true in Python
Program prints the else condition even when the if statements are true in Python

Time:09-23

I'd like to convert my Celsius temp to fahrenhite and vice versa. This is the code I've given:

temperature=int(input('what is the temperature? '))

type=input('is it in celsius or fahrenheit: ')

if temperature == 'celsius':

converted_temp = (temperature*9/5) 32 

print("The converted temp in fahrenheitis: ",converted_temp) 

elif temperature == 'fahrenheit':

converted_temp = (temperature-32)*5/9 

print('The converted temperature in celsius is:',converted_temp) 

else:

print("SORRY! Enter either Celsius or Fahrenheit") 

CodePudding user response:

Just don't use type word, it is registered as a special word in python

temperature_type = input('is it in celsius or fahrenheit: ')
temperature_value = int(input('what is the temperature? '))

if temperature_type == 'celsius': 
    converted_temp = (temperature_value * 9 / 5)   32 
    print("The converted temp in fahrenheitis: ", converted_temp) 
elif temperature_type == 'fahrenheit': 
    converted_temp = (temperature_value - 32) * 5 / 9 
    print('The converted temperature in celsius is:', converted_temp) 
else: 
    print("SORRY! Enter either Celsius or Fahrenheit")

CodePudding user response:

You've put

if temperature == 'celsius'

Instead of

if type == 'celsius'

So the script is looking at the temperature integer instead of the type string.

  • Related