Python函数输入

时间:2013-05-19 12:02:00

标签: python

我正在尝试在代码学院教自己Python,并编写了以下基本代码,这些代码的结果不是'Please Enter a Valid Number',而且我得到的消息是"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"

原始作业是:

  

编写一个名为area_of_circle的函数,该函数将radius作为输入并返回圆的区域。圆的面积等于pi乘以半径的平方。 (使用math.pi表示Pi。)

4 个答案:

答案 0 :(得分:5)

程序中的错误:

  1. raw_input()会返回一个字符串,您必须先转换为floatint
  2. 在python
  3. 中进行类型检查是一个坏主意
  4. math.pi()不是一个只使用math.pi
  5. 的函数

    使用exception handling将字符串转换为数字:

    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 :(得分:2)

raw_input() 始终返回str。您需要将其传递给另一个类型的构造函数才能进行转换。

radius_val = float(radius)

答案 2 :(得分:1)

您可以在阅读输入时输入它:

radius = float(raw_input("Enter the radius of your circle"))

答案 3 :(得分:0)

如果输入是int或float(这没有多大意义),看你想要不同的路径

if type(radius) == int:
        return math.pi() * radius**2
elif type(radius) == float:

由于raw_input()的字符串的解释可以是int或float,你应该像这样评估它:

import ast
radius = ast.literl_eval(raw_input("Enter the radius of your circle"))

这样你可以避免尝试检查它是浮点数还是int等......

>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 2.5
<type 'float'>
>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 5
<type 'int'>