I am trying to teach myself Python on code academy and have written the following basic code, which is not working as whatever the input the outcome is 'Please Enter a Valid Number' and I get a message saying "Oops, try again! Make sure area_of_circle takes exactly one input (radius)."
import math
radius = raw_input("Enter the radius of your 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 a valid number'"
print "Your Circle area is " + area_of_circle(radius) + " units squared"
The original assignment is:
Write a function called
area_of_circlethat takesradiusas input and returns the area of a circle. The area of a circle is equal to pi times the radius squared. (Use the math.pi in order to represent Pi.)
4 Answers 4
Errors in your program:
raw_input()returns a string, you've to convert to afloatorintfirst.- Type checking is a bad idea in python
math.pi()is not a function just usemath.pi
Use exception handling to convert the string into a number:
import math
radius = raw_input("Enter the radius of your circle: ")
def area_of_circle(radius):
try :
f = float(radius) #if this conversion fails then the `except` block will handle it
return math.pi * f**2 #use just math.pi
except ValueError:
return "'Please enter a valid number'"
print "Your Circle area is {0} units squared".format(area_of_circle(radius))
1 Comment
raw_input() always returns a str. You need to pass it to another type's constructor in order to convert it.
radius_val = float(radius)
Comments
You can type cast it while reading the input:
radius = float(raw_input("Enter the radius of your circle"))
Comments
Seeing as you want different paths for if the input is a int or float (which doesn't make much sense)
if type(radius) == int:
return math.pi() * radius**2
elif type(radius) == float:
As the interpretation of raw_input()'s string could be either int or float you should evaluate it like so:
import ast
radius = ast.literl_eval(raw_input("Enter the radius of your circle"))
This way you can avoid trying to check if it is a float or int etc...
>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 2.5
<type 'float'>
>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 5
<type 'int'>
type(variablename) == sometype. At best, useisinstance(variablename, sometype). Or just don't test at all, assume it's a valid type, that's more pythonic. Catch the exception if need be, but don't test for specific types.math.piis a number, not a function, so you'll need to changemath.pi()tomath.pi.