gpt4 book ai didi

Python编程缩进问题

转载 作者:太空宇宙 更新时间:2023-11-04 09:02:00 25 4
gpt4 key购买 nike

我想知道是否有人可以阅读这段代码并告诉我为什么会这样。我不是第一个遇到这个问题的人,但我环顾四周,无法在书中或其他地方找到答案。

这一定是小事,但我看不到。

# This program will find and calculte the radius
# area and circumference of a circle.

def main():
print('Radius\tArea\tCircumference')
print('----------------------------')
print()
for radius in range(1, 11):
for area in range(1, 11):
for circumference in range(1, 11):
pi = 3.14
diameter = radius * 2
radius = diameter / 2
area = pi * radius**2
circumference = (2 * pi) * radius

print(radius, '\t', area, '\t',format(circumference, '.2f'))



main()

输出:

Radius  Area    Circumference
----------------------------

1.0 3.14 6.28
2.0 12.56 12.56
3.0 28.26 18.84
4.0 50.24 25.12
5.0 78.5 31.40
6.0 113.04 37.68
7.0 153.86 43.96
8.0 200.96 50.24
9.0 254.34 56.52
10.0 314.0 62.80
>>>

输出在前两列中对齐,但第三列中十个中的四个似乎在右侧制表符。 ??

最佳答案

为了保证对齐,可以先把每个数字做成固定宽度的字符串。

def main():
print('Radius\tArea\tCircumference')
print('----------------------------')
print()
for radius in range(1, 11):
for area in range(1, 11):
for circumference in range(1, 11):
pi = 3.14
diameter = radius * 2
radius = diameter / 2
area = pi * radius**2
circumference = (2 * pi) * radius

#print(radius, '\t', area, '\t' , format(circumference, ".2f"))
radius_str = "%0.2f" % radius
area_str = "%0.2f" % area
circumference_str = "%0.2f" % circumference
print("%6s\t%6s\t%6s" % (radius_str, area_str, circumference_str))

main()

输出:

Radius  Area    Circumference
----------------------------

1.00 3.14 6.28
2.00 12.56 12.56
3.00 28.26 18.84
4.00 50.24 25.12
5.00 78.50 31.40
6.00 113.04 37.68
7.00 153.86 43.96
8.00 200.96 50.24
9.00 254.34 56.52
10.00 314.00 62.80

关于Python编程缩进问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24357565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com