Home > Mobile >  Why the While loop continues and how to calculate the average based on numbers input?
Why the While loop continues and how to calculate the average based on numbers input?

Time:12-25

Hi I'm trying to solve this coding homework:

Write a program that always asks the user to enter a number. When the user enters the negative number -1, the program should stop requesting the user to enter a number. The program must then calculate the average of the numbers entered excluding the -1.

I define the while loop to make sure it keeps asking, as:

while n != -1
 str(input("enter your number:"))

But whenever I try to input -1, it just keeps on asking to enter the number regardless. Also, I'm not sure what is the best way to define the average excluding -1, none of the lessons prior to this assignment talked about this. I have Googled about it but none of the examples match this particular assignment, even fumbling around did not help.

Thank you for your help :)

CodePudding user response:

Presumably n is meant to be the user input, but you're never assigning a value to n. Did you mean to do this?

n = str(input("enter your number:"))

Also, you're comparing n to -1, but your input isn't a number; it's a string. You can either convert the input to a number via n = int(input(...)), or compare the input to a string: while n != '-1'.

CodePudding user response:

You could ask for a number the if it is not equal to -1 enter the while loop. So the code would be:

n = float(input("What number?"))
if n != -1:
    sum  = n
    nums_len = 1
    while n != -1:
        sum  = 1
        nums_len  = 1
        n = float(input("What number?"))
print("The average is", str(sum/nums_len))
  • Related