[Tutor] Fahrenheit to Celsius Conversion with if else statements

William Gan ganwilliam at outlook.com
Mon Jun 12 10:17:18 EDT 2017


Good day Everybody,

I am practicing coding when I encountered a problem with the if and else statements in my code. Hope someone can help me understand my mistake.

The following is my code to convert Fahrenheit to Celsius and vice-versa:

print('Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.')
unit = input('Enter C or F:')
temp = int(input('Enter temperature:'))

if unit == 'C':
    f = (temp + 32) * 9 / 5
    print(str(temp) + ' C is equivalent to ' + "%.2f" % f + ' F.')
else:
    c = (temp - 32) * 5 / 9
    print(str(temp) + ' F is equivalent to ' + "%.2f" % c + ' C.')

OUT:
Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.
Enter C or F:f
Enter temperature:212
212 F is equivalent to 100.00 C.

However, when I entered C, the else block was executed instead. The if block was skipped.



Enter C for Celsius to Fahrenheit or F for Fahrenheit to Celsius.

Enter C or F:c

Enter temperature:100

100 F is equivalent to 37.78 C.

I could not figure out my mistake.

For advice, please. Thank you.

Best regards
william



More information about the Tutor mailing list