1

I'm having a user input info for a program and I'm having trouble storing information from user without it overwriting in a loop. My code as follows:

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]

Is there a way to store each radii input into a variable to be added into the list cValue?

Output:

Enter the number of circles: 2
Enter the radius of circle 1: 7
Enter the radius of circle 2: 4
1
  • circle_value.append(float(circles)) should do the trick instead of circle_value = float(circles) Commented Oct 28, 2015 at 19:49

1 Answer 1

4

You want to initialize a list to append the values to before you enter the loop:

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)

If you run the program with the following input:

Enter the number of circles: 2
Enter the radius of circle 1: 5
Enter the radius of circle 2: 7

The output will be

[5.0, 7.0]

And the individual values on that list can be accessed like this:

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)
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. appreciate the answer. I figured if i did .append() it would have done the same but now I know.
@Compscistudent Nearly. If you had initialized a list to save the circle values in prior to the loop (call it circle_values if you like), then instead of circle_values.append(circle_value) inside the loop you could also write circle_values += [circle_value] to accomplish the appending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.