0

I wish to accept a number in float from the user and give back an answer multiplying that number with pi value = 3.14

heres my code:

print "Enter a no."
n = raw_input('enter here: ')
result = 1
def gen_pi(x):
    result = x*3.14
    return float(result)

gen_pi(n)

its giving me an error of not being able to multiply non int sequence with float. what does it mean? anything wrong with the code?

aneroid
  • 12,983
  • 3
  • 36
  • 66
Tej
  • 1
  • 1
  • 2

1 Answers1

0

The result of raw_input is a str which means that n is a str and then in your function, x is a str which can't multiply a float.

you'll want to convert x into a float before multiplying by pi.

There are lots of places to do this, but I'd recommend doing it before passing to gen_pi:

gen_pi(float(n))

This way, gen_pi can always assume it's working with a float and that code can be simplified:

def gen_pi(x):
    return x * 3.14

Also note that if you want more precision (and possibly a bit more code clarity), you can use math.pi:

import math
def gen_pi(x):
    return x * math.pi
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • And then additionally, since `3.14` is already a float, `result` (in `gen_pi`) will also be a float. So `return float(result)` should be just `return result`. – aneroid Dec 14 '15 at 03:19
  • 1
    @aneroid -- Right. I was apparently writing that up as you were commenting. – mgilson Dec 14 '15 at 03:20