Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

first item from user input not being included using append function

I’m trying to create a list of numbers from user input.

I tried to use ‘append’ to create the list so I am then able to calculate the average, but ‘append’ is not including the first number entered by the user.

Any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance!

list_number = []  
number = float(input("Please enter any number (enter (-1) when done): "))



while number != -1:         
    number = float(input("Please enter any number (enter (-1) when done): "))
    list_number.append(number)
    if number == -1 : 
        print("You have exited the loop")
        break


print(list_number)
total_num = sum(list_number)
num_entries = len(list_number)
average = total_num / num_entries
print("Average: ", average)

>Solution :

Welcome to StackOverflow! It looks like you simply forgot to list_number.append(number) after the first number = .... However, the while loop used here should be replaced with a "do while" to avoid repetition. To do this in Python, just while True and add a break statement if number == -1 as you already have.

For example:

list_number = []  

while True:
    number = float(input("Please enter any number (enter (-1) when done): "))
    if number == -1: 
        print("You have exited the loop")
        break
    else:
        list_number.append(number)

print(list_number)
total_num = sum(list_number)
num_entries = len(list_number)
average = total_num / num_entries
print("Average: ", average)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading