0

So I'm trying to input a division problem as a parameter, and I am always getting 0 when the answer is < 1. I know why this is happening but I'm not sure how to fix this so it gives a decimal answer.

def division(x): print x Where "x" is 1/2 and the code prints ".5"

I'm using JES version 5.020. Any guidance would be much appreciated!

Kramer M.
  • 1
  • 1

2 Answers2

0

use the float() function.

5/2=2
float(5)/float(2)=2.5

Phonzi
  • 144
  • 3
  • 9
0

First of all, there is no point in having a function called division if all it does is print the input.

Now to the actual problem. You are using python 2. In python 2, division of integers is always an integer. So 1/3 (which should be equal to 0.33) is just 0.

The solution is to convert at least one of the numbers to float. This can be done in the following ways:

  1. float(1)/3
  2. 1.0/3

And yes, in your current setup, this division will happen before the numbers are passed to your function. So your function works perfectly, it is the input that needs to change.

Edit:

If you cannot alter the input and need to support floating point division of integers use the future module. This brings some of python 3 features to python 2.

Add this line to the beginning of your code:

from __future__ import division
shish023
  • 533
  • 3
  • 10
  • Is what I'm trying to do even possible? The input cannot be converted to a floating point number before the division happens. I want the user just to specify the parameter "1/2" and have the function know that it is .5 instead of 0. – Kramer M. Feb 19 '17 at 17:31
  • It is possible but I don't understand why you would want to do that. Numerical inputs are expected to be numbers and not fractional representations of numbers. At least that's what the programming language assumes. If you want to allow users to be able to input numbers in a representation not supported by the language, you should input as a string and then process the input as you like. But luckily in your case a small modification can get you the results you want. Please see my edited answer. – shish023 Feb 19 '17 at 19:38
  • Yeah, I've tried `from __future__ import division` but it won't load and gives an invalid syntax error. I'm not really sure where to go from here. – Kramer M. Feb 20 '17 at 02:08
  • Can you show us the exact code and the exact error you see? Also this might be an overkill but can you just move to python 3? – shish023 Feb 20 '17 at 21:41