How to find the mean of a list - python

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

#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

There is good thing called statistics.mean:
from statistics import mean
mean(your_list)

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

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)

Related

I want to make an calculator for average but i'm facing some issues

I want to make an calculator for average but i'm facing some issues. I want the numbers entered by the users come as a print statement but it is just throwing the last entered value.Here is my code.
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: ", inp)
print(f"average is = ", average)
Solution
we can print the list
numlist = list()
while True:
inp = input(f"Enter a number, (Enter done to begin calculation): ")
if inp == 'done':
break
value = float(inp)
numlist.append(value)
average = sum(numlist) / len(numlist)
print(f"The Entered numbers are: {numlist}")
print(f"average is = ", average)
As I understand, you want to print all the user inputs, however, as I see in your code, you are printing just a value but not the storing list, try to change your code to print(f"The Entered numbers are: ", numlist)
You are telling the user that their entered numbers are the last thing they typed in input, which will always be "done" because that is what breaks out of the loop. If you want to print the entered numbers; print numlist instead of inp.

How to calculate average and range after input into list?

I need some help regarding calculating averages and ranges. I am using built-in functions such as sum(), len(), etc. and cannot seem to calculate the average or range. I am using it to write a small piece of code for fun but cannot seem to get it to work. any help is much appreciated. Thank you!
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" + sum(number_list) / len(number_list))
print("Here is the range:", range(number_list))
quit()
Change
if str.isdigit(input_number) == True:
number_list.append(input_number)
to
if input_number.isdigit():
number_list.append(int(input_number))
The error is because you're trying to do those operations on a list of strings.
You can also remove the check against True since that is implicitly checking the truthiness and since input_number is already a str, you can call the isdigit() method directly.
The problem is that you are appending strings to the list rather than integers and then you are applying arithmetic operations on it. So first you should convert the input number to int type.
Secondly range function will not give you the range of a list rather then it returns a sequence.
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
input_number=int(input_number)
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" , sum(number_list) / len(number_list))
print("Here is the range:", max(number_list)-min(number_list))

How to make a "while" loop using input from user?

Currently using 3.8.1.
I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.
while True:
question = input("Would you like to save?")
if question.lower() in ('yes'):
print("Saved!")
print("Select another option to continue.")
break
if question.lower() in ('no'):
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
How about including less than / great than clauses in your if statements?
while True:
# get user input:
user_input = input("Would you like to save? ")
# convert to int:
number = int(user_input)
if number <= 100:
print("Saved!")
print("Select another option to continue.")
break
elif number > 100:
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
you need to extract the number from the input and then run your conditional evaluation of the inputed value.
while True:
input_val = input("Enter a #?")
try:
num=int(input_val)
except ValueError:
print("You have entered an invalid number. please try again")
continue
if num == 1:
print("bla bla")
elif num ==2:
print("bla bla 2")
else:
...
input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want
while True:
answer = input("How many dogs do you have?")
if answer.isnumeric():
num_dogs = int(answer)
else:
print("Please input a valid number")
I think you maybe want a list instead of a tuple.
Could this work:
while True:
number = input("Enter a number?")
if int(number) in list(n for n in range(100)):
print("lower!")
elif int(number) in [100]:
print ("exact")
else:
print("higher")

Can't convert string to float in Python

I'm trying to write a small program to calculate numbers from the user. There's also some conditions to check if the number is positive or the user just hits enter. For some reason, I can't get the data variable to convert into a float.
The error occurs on line 5 where I get the error "ValueError: could not convert string to float:" I've tried so many combinations now, and tried to search StackOverflow for the answer, but without any luck.
How can I convert the input into a float? Thanks in advance for any help!
sum = 0.0
while True:
data = float(input('Enter a number or just enter to quit: '))
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
Instead of having the user press enter to quit, you can instead write:
sum = 0.0
while True:
data = float(input('Enter a number or "QUIT" to quit: '))
if data.upper() != "QUIT":
if data < 0:
print("Sorry, no negative numbers!")
continue
elif data == "":
break
number = data
sum += data
print("The sum is", sum)
You can't convert an empty string to a float.
Get the user's input, check if it's empty, and if it's not, then convert it to a float.
You can check if the data is empty before convert to float with this way:
sum = 0.0
while True:
data = input('Enter a number or just enter to quit: ')
if data != "":
data = float(data);
if data < 0:
print("Sorry, no negative numbers!")
continue
number = data
sum += data
print("The sum is", sum)
else:
print("impossible because data is empty")
You have to first check for the empty string and then convert it to float.
Also you might want to catch malformed user input.
sum = 0.0
while True:
answer = input('Enter a number or just enter to quit: ')
if not answer: # break if string was empty
break
else:
try:
number = float(data)
except ValueError: # Catch the error if user input is not a number
print('Could not read number')
continue
if number < 0:
print('Sorry, no negative numbers!')
continue
sum += data
print('The sum is', sum)
In python, empty things like '' compare like False, it's idiomatic to use this in comparisons with if not <variable> or if <variable>.
This also works for empty lists:
>>> not []
True
And for None
>>> not None
True
And pretty much everything else that could be described as empty or not defined like None:

Python: How to keep repeating a program until a specific input is obtained? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have a function that evaluates input, and I need to keep asking for their input and evaluating it until they enter a blank line. How can I set that up?
while input != '':
evaluate input
I thought of using something like that, but it didn't exactly work. Any help?
There are two ways to do this. First is like this:
while True: # Loop continuously
inp = raw_input() # Get the input
if inp == "": # If it is a blank line...
break # ...break the loop
The second is like this:
inp = raw_input() # Get the input
while inp != "": # Loop until it is a blank line
inp = raw_input() # Get the input again
Note that if you are on Python 3.x, you will need to replace raw_input with input.
This is a small program that will keep asking an input until required input is given.
we should keep the required number as a string, otherwise it may not work. input is taken as string by default
required_number = '18'
while True:
number = input("Enter the number\n")
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
or you can use eval(input()) method
required_number = 18
while True:
number = eval(input("Enter the number\n"))
if number == required_number:
print ("GOT IT")
break
else:
print ("Wrong number try again")
you probably want to use a separate value that tracks if the input is valid:
good_input = None
while not good_input:
user_input = raw_input("enter the right letter : ")
if user_input in list_of_good_values:
good_input = user_input
Easier way:
required_number = 18
user_number = input("Insert a number: ")
while f"{required_number} != user_number:
print("Oops! Something is wrong")
user_number = input("Try again: ")
print("That's right!")
#continue the code

Categories

Resources