Home > Back-end >  How can I add more prompts with a for/while loop to this average calculator that is using input?
How can I add more prompts with a for/while loop to this average calculator that is using input?

Time:09-29

I'm trying to build an average calculator. I'd like to take the following code (with two prompts for user input) and turn it into a loop, and eventually add more prompts. I tried to use a while loop, but when I did, not even a prompt would show up.

Here's my code, which is intended to append two numbers to a list and average the results:

a_list = []
max_length_list = len(a_list)
length = len(a_list)
prompt = input("Insert Number Here:\n")
float(prompt)
a_list.append(prompt)
prompt2 = input("Insert Number Here:\n")
float(prompt2)
a_list.append(prompt2)
average = sum(a_list) / len(a_list)
print(average)

CodePudding user response:

Your question is kind of unclear but i assume you want to know how to use a loop for that that collects two values.

max_length_list = 2
a_list = []
for _ in range(max_length_list):
    prompt = input("Insert Number Here:\n")
    prompt = float(prompt)
    a_list.append(prompt)

average = sum(a_list) / len(a_list)
print(average)

You need to assign the conversion to the variable prompt.

CodePudding user response:

You can either set the max length or make it dynamic.

Max length:

a_list = []
max_input = input("how many numbers do you need to avg?: ")
for _ in range(int(max_input)):
    prompt = input("Insert Number Here:\n")
    a_list.append(float(prompt))
average = sum(a_list) / len(a_list)
print(average)

Dynamic:

a_list = []
while True:
    prompt = input("Insert Number Here (type 'x' to stop):\n")
    if prompt == 'x':
        break
    a_list.append(float(prompt))
average = sum(a_list) / len(a_list)
print(average)
  • Related