0

New to python and writing a simple code to convert Fahrenheit to Celcius.

Can someone tell me why these two lines of code give different results?

cConvert = (number - 32)/(9/5)

cConvert = (number - 32)/1.8

9/5 = 1.8 but how can I write the code without having to compute 9/5 myself?

Thanks

5 Answers5

1

In Python 2, this is an int result:

>>> 9/5
1

But this is a float result:

>>> 9/5.0
1.8

As is this:

>>> 9.0/5
1.8

So add .0 to one of the opperands in the equations to make the operation happen as floats.

dawg
  • 98,345
  • 23
  • 131
  • 206
1

Assuming this is Python 2, you can fix this either by explicitly using float literals 9./5 or 9/5. or 9./5. (you can add 0 after the . if you like, but it's not necessary; the trailing dot makes float literals by itself), or you can move to Py3 semantics. Your code works exactly as written if you add:

from __future__ import division

to the top of your source file to get Py3 division rules. If you want floor division, you can use 9 // 5, but otherwise, with Py3 division, int / int always results in float.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
0

You need to change either 9 or 5 into float like 9.0/5 or 9/5.0, or both. If not, 9/5 will return the integer part of result, 1.

ProtossShuttle
  • 1,623
  • 20
  • 40
0

If you're using Python 2, integer division produces an integer result, so you need to convert one or both of the operands to float to get the desired result. In Python 3, integer division produces a float result (even if the result is an exact integer), so in Python 3 the explicit conversion to float isn't needed.

Try the following:

cConvert = (number - 32)/(float(9)/5)

Or:

cConvert = (number - 32)/(9.0/5)

These should give you the result you're expecting, in both Python 2 and Python 3.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
0

Course you are using Python2.x.

Related questions:
How can I force division to be floating point in Python
Python integer division yields float

In Python3

Python 3.4.0 (default, Apr 11 2014, 13:05:18) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/5
1.8
>>> 9//5
1
Community
  • 1
  • 1
luoluo
  • 5,353
  • 3
  • 30
  • 41