我有一个程序的用户输入信息,我在用户存储信息时遇到问题而没有在循环中覆盖。我的代码如下:
def main():
total_circles = input("Enter the number of circles: ")
for number in range(1, int(total_circles) + 1):
circles = input("Enter the radius of circle {}: ".format(number))
circle_value = float(circles)
circle_value = [] + [circle_value]
有没有办法将每个半径输入存储到要添加到列表cValue
的变量中?
输出:
Enter the number of circles: 2
Enter the radius of circle 1: 7
Enter the radius of circle 2: 4
答案 0 :(得分:4)
您希望在进入循环之前初始化列表以附加值:
def main():
total_circles = input("Enter the number of circles: ")
circles = []
for number in range(1, int(total_circles) + 1):
circles.append(float(input("Enter the radius of circle {}: ".format(number))))
print(circles)
如果使用以下输入运行程序:
Enter the number of circles: 2
Enter the radius of circle 1: 5
Enter the radius of circle 2: 7
输出
[5.0, 7.0]
可以像这样访问该列表中的各个值:
circles[0] # 5.0, the value of circle 1 (stored at index 0)
circles[1] # 7.0, the value of circle 2 (stored at index 1)