如何根据 python 中给出的半径打印计算面积和周长的列表

how to print list of calculated area and circumferences from radius given in python

大家好,我有这个半径列表,分别为 5.2、7.0、12.5、7.7 和 23.5。 现在我需要根据给定的半径找到面积和周长 但是如何合并它并获得与下面相同的输出,而不是 1 对 1。

area = 3.14 * radius**2
circumference = 2 * 3.14 * radius

print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.\
      format(radius, area, circumference))

radius = 7.0
area = 3.14 * radius**2
circumference = 2 * 3.14 * radius

print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.\
      format(radius, area, circumference))

radius = 12.5
area = 3.14 * radius**2
circumference = 2 * 3.14 * radius

print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.\
      format(radius, area, circumference))

radius = 7.7
area = 3.14 * radius**2
circumference = 2 * 3.14 * radius

print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.\
      format(radius, area, circumference))

radius = 23.5
area = 3.14 * radius**2
circumference = 2 * 3.14 * radius

print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.\
      format(radius, area, circumference))

输出:

Radii: 5.2  Area: 84.9056   Circumference: 32.6560
Radii: 7.0  Area: 153.8600  Circumference: 43.9600
Radii: 12.5 Area: 490.6250  Circumference: 78.5000
Radii: 7.7  Area: 186.1706  Circumference: 48.3560
Radii: 23.5 Area: 1734.0650 Circumference: 147.5800

列出并循环:

for radius in [5.2, 7.0, 12.5, 7.7, 23.5]:
    area = 3.14 * radius**2
    ...

任何时候你想一遍又一遍地重复同样的任务,最好把它变成一个for循环。最好的方法是首先根据您的情况列出要更改的数据:

list_of_radii = [5.2, 7.0, 12.5, 7.7, 23.5]

接下来,您想对这些信息做些什么。所以for循环来了。

for radius in list_of_radii:
    # For loop body

这条线将穿过每个半径,从 5.2 开始...用它做点什么,然后循环到 7.0...用它做点什么,一直到 23.5。现在“body”就是你放置你想要完成的东西的地方。在你的情况下:

area = 3.14 * radius ** 2
circumference = 2 * 3.14 * radius
print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.format(radius, area, circumference))

这是取每个半径,计算面积和周长,然后打印出来。所以你的问题的解决方案如下所示:

list_of_radii = [5.2, 7.0, 12.5, 7.7, 23.5]

for radius in list_of_radii:
    area = 3.14 * radius ** 2
    circumference = 2 * 3.14 * radius
    print('Radii: {:.1f}\tArea: {:.4f}\tCircumference: {:.4f}'.format(radius, area, circumference))