0

Well I am having trouble to print numbers with decimal point. When I run python and ask it to do a division, in which the result must be a number with decimal point, it doesn't print the decimal point. For instance, I have just made this algorithm:

print 'Report card calculation' grade1 = input ('Insert the first grade: ') grade2 = input ('Insert the second grade: ') grade3 = input ('Insrt the third grade: ') media = (grade1 + grade2 + grade3) / 3 print 'Your final result is', media 

But when it prints the "media", the number which should have a decimal point doesn't come with a decimal point. How can I fix it?

1
  • what are your inputs? are they integers? Commented Jan 27, 2012 at 20:32

4 Answers 4

2

Simplest change: divide by 3.0 instead of 3:

media = (grade1 + grade2 + grade3) / 3.0 

This will ensure that the value assigned to media will be floating point even if the three grade variables hold ints.

Sign up to request clarification or add additional context in comments.

Comments

2

At the top of your file, add:

from __future__ import division 

or use 3.0 instead of 3. In Python 2, dividing two integers always produces an integer.

Comments

1

Your operation is handled as an integer division, try using 3.0 in place of 3, see what happens then.

Comments

1

When you divide two integers in Python 2.x, the result will be an integer. From the documentation on Numeric Types:

For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value.

To get the behavior you want, either add from __future__ import division to the top of your module to use the Python 3 division behavior, or change one the numerator or denominator (or both) to a float:

# either of the following would work media = float(grade1 + grade2 + grade3) / 3 media = (grade1 + grade2 + grade3) / 3.0 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.