Python Function inputs -
i trying teach myself python on code academy , have written following basic code, not working whatever input outcome 'please enter valid number'
, message saying "oops, try again! make sure area_of_circle takes 1 input (radius)."
import math radius = raw_input("enter radius of circle") def area_of_circle(radius): if type(radius) == int: return math.pi() * radius**2 elif type(radius) == float: return math.pi() * radius**2 else: return "'please enter valid number'" print "your circle area " + area_of_circle(radius) + " units squared"
the original assignment is:
write function called
area_of_circle
takesradius
input , returns area of circle. area of circle equal pi times radius squared. (use math.pi in order represent pi.)
errors in program:
raw_input()
returns string, you've convertfloat
orint
first.- type checking bad idea in python
math.pi()
not function usemath.pi
use exception handling convert string number:
import math radius = raw_input("enter radius of circle: ") def area_of_circle(radius): try : f = float(radius) #if conversion fails `except` block handle return math.pi * f**2 #use math.pi except valueerror: return "'please enter valid number'" print "your circle area {0} units squared".format(area_of_circle(radius))
Comments
Post a Comment