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

Question:

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 🙂

Asked By: Valkz

||

Answers:

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'.

Answered By: Simon Lundberg

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))
Answered By: iamdeedz

Thanks everyone, this is the final code with the correct values that gives the average of user inputs

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

Answered By: Valkz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.