Beginner: Trying to get REAL NUMBERS from %d command

Hans Mulder hansmu at xs4all.nl
Sun Dec 30 18:17:44 EST 2012


Hello,

Python does not support REAL numbers.  It has float number, which
are approximations of real numbers.  They behave almost, but not
quite, like you might expect.

It also has Decimal numbers.  They also approximate real numbers,
but slightly differently.  They might behave more like you'd expect
if you're used to an electronic calculator.


On 30/12/12 23:37:53, Alvaro Lacerda wrote:
> The code I wrote is supposed to ask the user to enter a number;
> Then tell the user what's going to happen to that number (x / 2 + 5) ;
> Then give the user an answer;
> 
> I succeeded getting results from even numbers, but when I try diving
> an uneven number (i.e. 5) by 2, I get only the whole number (i.e. 2) 
> 
> I'm trying to get full number result using the %d command, I've tried
> to add the line "from __future__ import division" to the beginning of
> my code, but I haven't been succeeded.
> 
> I also tried making my numbers decimals (i.e. 2.0 instead of just 2)

Errrhm, 2.0 is a float.

To get decimal numbers, you'd need to import the Decimal module.



> Below is my program and thanks for the help :)
> 
> 
> 
> from __future__ import division;
> 
> def decimal_percent_test():
>     number = input("Enter a number: ");
>     print number, "will be divided by 2 then added by 5!";
>     print " %d divided by %d is %d plus %d is... %d !" %(
>           number,2,number/2,5,number/2+5);

The %d code will convert your number to a whole number.
as you found out.

The simplest way to make this program work, is to use the %s
code, which doesn't convert to a different type of number:

from __future__ import division;

def decimal_percent_test():
    number = input("Enter a number: ")
    print number, "will be divided by 2 then added by 5!"
    print " %s divided by %s is %s plus %s is... %s !" % (
                number, 2, number/2, 5, number/2+5)

while True:
    decimal_percent_test()


Enter a number: 10
10 will be divided by 2 then added by 5!
 10 divided by 2 is 5.0 plus 5 is... 10.0 !
Enter a number: 11
11 will be divided by 2 then added by 5!
 11 divided by 2 is 5.5 plus 5 is... 10.5 !
Enter a number: x
Traceback (most recent call last):
  File "test.py", line 11, in <module>
    decimal_percent_test()
  File "test.py", line 5, in decimal_percent_test
    number = input("Enter a number: ")
  File "<string>", line 1, in <module>
NameError: name 'x' is not defined



Hope this helps,

-- HansM




More information about the Python-list mailing list