首页 > 编程知识 正文

利用python求圆的面积,python计算半径为5的圆的面积

时间:2023-05-06 05:14:00 阅读:286575 作者:963

今天根据一个如何计算圆形的面积展开对python 中变量的灵活运用进行彻底的大起底。

最简单的计算代码,比如我们需要计算半径是5毫米的圆的面积。

根据圆的面积公式s=pai*r*r

代码分享

print(3.14*5*5)

*********************

>>> print(3.14*5*5)

78.5

>>>

------------------------------

如果我们的半径采用在键盘上动态输入。

代码应该是:

r = input("radius of circle=?")

s = 3.14 * r * r

print("Area of circle=", s)

**********************

>>> r = input("radius of circle=?")

radius of circle=?5

>>> s = 3.14 * r * r

Traceback (most recent call last):

File "", line 1, in

TypeError: can't multiply sequence by non-int of type 'float'

>>>

>>> print("Area of circle=", s)

Traceback (most recent call last):

File "", line 1, in

NameError: name 's' is not defined

>>>

先来看第2句的提示,类型错误。字符串不能进行浮点数的计算

TypeError: can't multiply sequence by non-int of type 'float'

我们修改代码,让pai =3.

>>> s = 3 * r * r

Traceback (most recent call last):

File "", line 1, in

TypeError: can't multiply sequence by non-int of type 'str'

意思是字符串不能进行平方运算。

我们修改成以下代码

>>> s = 3 * r

>>> print(s)

555

我们从结果来看,我们上面输入的

r = input("radius of circle=?")

的r的类型是字符串。

如何得知?

也可以让系统输出我们输入的r变量的类型

>>> type(r)

-------------------

我们更改下r的输入类型。

r = int(input(”radius of circle=?“))

s = 3.14 * r * r

print("area of circle=?",s)

通过以上的测试,我们知道,有时候代码可以写的很简单,就是直接输出

print(3.14*r*r)

一句话就可以了。

但是有时候,为何学习了解一门语言。在平时的多种场合,我们不能总是很简单的用

一行代码就可以摆平所有情况。

如果需要编写成一个函数

我们可以先定义一个方法,然后调用这个方法,传入参数,这样来写。

>>> def A(r):

... Pai = 3.142

... return Pai*r*r

...

>>> print(A(5))

78.55

>>>

**********************************************

我们在写这个函数的时候,特别需要注意在函数的定义阶段,在电脑中输入的时候,缩进必须一致,否则很打击你的学习自信心。

比如,我们输入了第一行def A(r):后。

这里需要注意的是,括号一定不能用中文输入法,然后后面有个冒号

然后回车,第二行,第三行一定要缩进相同的空格。否则。输入就失败了。

然后系统

def A(r):

空格空格pai = 3.142

空格空格return pai*r*r

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。