Skip to main content
 首页 » 编程设计

Python 函数输入

2025年05月04日11fff_TT

我正在尝试在代码学院自学 Python 并编写了以下基本代码,无论输入结果是什么,它都不起作用 'Please Enter a Valid Number' 我得到了消息说 “糟糕,再试一次!确保 area_of_circle 正好接受一个输入(半径)。”

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" 

原来的作业是:

Write a function called area_of_circle that takes radius as 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.)

请您参考如下方法:

程序中的错误:

  1. raw_input() 返回一个字符串,您必须先转换为 float 或 int。
  2. 类型检查在 python 中是个坏主意
  3. math.pi() 不是一个函数,只是使用 math.pi

使用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))