Aaria
Aaria

Reputation: 289

How to find the mean of a list

I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.

I want to be able to find the mean of all the numbers that are in the list and print out the result. And in the String section I want to be able to print out everything within the string and its length. User types 'save' to exit and if input is valid that's caught.

Numbers = []
String = []

while(True):
    user_input = input("What's your input? ")
    if user_input == "save":
        break
    elif user_input.isdigit():
        Numbers.append(user_input)
        for i in range(len(Numbers)):
            Numbers[i] = int(Numbers[i])
            print(sum(Numbers)/len(Numbers)
    elif isinstance(user_input, str):
        String.append(user_input)
        print(String)
        print (len(String)-1)
    else:
        print("Invalid input.")
        break

Upvotes: 0

Views: 617

Answers (4)

Yulin Zhou
Yulin Zhou

Reputation: 1

I found other more convenient way to produce the mean: Use statistics model and output the mean.

#import useful packages
import statistics

#Create an empty list
user_list = []

#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")

#game start
while True:
    #user will input their number into a the empty list
    user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")

#help the user to get an average number
if user_number == 'a':
    num_average = statistics.mean(user_list)
    print("The mean is: {}.".format(num_average))
    break #Game break
else:
    user_list.append(int(user_number))
    print(user_list)

Upvotes: 0

Rehan Shikkalgar
Rehan Shikkalgar

Reputation: 1047

#use isalpha to check enterted input is string or not
#isalpha returns a boolean value

Numbers = []
String = []

while(True):
    user_input = input("input : ")
    if user_input == "save":
        break
    elif user_input.isdigit():
        Numbers.append(int(user_input))
        print(sum(Numbers)/len(Numbers))
    elif user_input.isalpha():
        String.append(user_input)
        print(String)
        print (len(String))
    else:
        print("Invalid input.")
        break

Upvotes: 2

vishes_shell
vishes_shell

Reputation: 23564

There is good thing called statistics.mean:

from statistics import mean
mean(your_list)

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49920

You are using Length, which has not been defined. I think what you wanted was

print(sum(Numbers)/len(Numbers))

and you probably don't want it inside the loop, but just after it (although that might be another typo).

Upvotes: 0

Related Questions