How to store arbitrary number of inputs from user? - python

Just wondering how I would store the inputs for an average sum of square roots problem.
The user can input as many numbers as they until they type 'end'
here is what i have for that
while(True):
x = input("Enter a number please:")
if x == 'end':
break

You can append these values to a list. Sum and then divide by the length for the average.
nums = []
while True:
x = input("Enter a number:")
if x == 'end':
avg = sum(nums) / len(nums)
print("And the average is....", avg)
break
elif x.isdigit():
nums.append(int(x))
else:
print("Try again.")

The next thing you'd want to learn about is a data structure such a list. You can then add items to the list on the fly with list.append.
However, it's noteworthy that where ever you're learning Python from will certainly go over lists at one point or another.

If you mean that you want to store all the x values given, just use a list. l = [] l.append(x).

Related

A program that takes user input, stores it into a list, then displays data about the list

I'm trying to solve the following problem:
Write a program that allows a user to keep inputting numbers until 0 is entered. The program should store the numbers in a list, then display the following data:
The list of numbers in ascending order
The lowest number on the list
The highest number in the list
The total of the numbers in the list
The average of numbers in the list
Here's what I have so far:
count = 0
list = []
total = 0
average = 0
index = 0
while True:
userInput = int(input("Enter a number:"))
if userInput == 0:
break
for i in range(userInput):
list.append(i)
list.sort()
print(list)
min_value = min(list)
max_value = max(list)
print("the min value is", min_value)
print("the max value is", max_value)
while index < len(list):
list[index] = int(list[index])
index += 1
for j in list:
total += j
print("the total is", total)
average = total/len(list)
print("the average is", average)
The program creates a weird list, that doesn't look anything like the user input. How can I solve this issue? It would be easier if I knew the length of the list, then I could use the range function and write to the list that way, but the length of the list is up to the user :/
Here's how you can do it:
user_data = [] # Dont name variables that can clash with Python keywords
while True:
userInput = int(input("Enter a number:"))
if userInput == 0:
break
else:
user_data.append(userInput) # append the value if it is not 0
print("The list in ascending order is:", sorted(user_data)) # Ascending order of list
print("the max value is", max(user_data)) # max value of list
print("the min value is", min(user_data)) # min value of list
print("the total is", sum(user_data)) # total of list
print("The average is", sum(user_data)/len(user_data)) # average of list
What you were doing wrong?
Naming a list to a Python keyword is not a good habit. list is a keyword in Python.
Biggest mistake:for i in str(userInput): Appending string of the number instead of int. How will you get the max, min, or total with a string?
You don't need to create one more loop for appending. You can use the same while loop.
Calculating total on your own through a loop is not a bad thing. Instead, I would say a good way to learn things. But I just wanted to tell you that you can use sum() to get the total of a list.
list.sort() will sort the list and print(list.sort()) would lead to None because it just sorts the list and doesn't return anything. To print sorted list use sorted(listname)
Sample Output:
Enter a number:12
Enter a number:2
Enter a number:0
The list in ascending order is: [2, 12]
the max value is 12
the min value is 2
the total is 14
The average is 7.0
I hope you understand and work on your mistakes.

How to remember previous numbers inputted in loop?

What I want to do, is to write a program that given a sequence of real numbers entered by the user, calculates the mean. Entering the sequence should be finished by inputting ’end’. To input more than 1 number I try:
num=input("Enter the number: ")
while num!="end":
num = input("Enter the number: ")
But I don't want the program to "forget" the first 'num', because I'll need to use it later to calculate the mean. What should I write to input and then use more than one value, but not a specific number of values? User should can enter the values until they enter 'end'. All of values need to be use later to calculate the mean. Any tip for me?
First, define an empty list.
numbers = []
Then, ask for your input in an infinite loop. If the input is "end", break out of the loop. If not, append the result of that input() to numbers. Remember to convert it to a float first!
while True:
num = input("Enter a number: ")
if num == "end":
break
numbers.append(float(num))
Finally, calculate the mean:
mean = sum(numbers) / len(numbers)
print("Mean: ", mean)
However, note that calculating the mean only requires that you know the sum of the numbers and the count. If you don't care about remembering all the numbers, you can just keep track of the sum.
total = 0
count = 0
while True:
num = input("Enter a number: ")
if num == "end":
break
total += float(num)
count += 1
print("Mean: ", total / count)
Mean is sum of all nos/total nos. Let's take input from user and add it to list, because we can easily use sum() function to find sum and len() function to find total nos. Your code:
obs=[]
while True:
num=input("Enter number: ")
if num=="end":
break
else:
obs.append(int(num))
print("Mean: ",(sum(obs)/len(obs)))

How do I make n-amount of inputs in a for-loop and use all the inputs later?

Here there are a "num" amount of inputs. How do I get the nth input value?
num = input("How many values?")
for x in range(0, int(num)):
ok = input()
Store inputs in list.
num = input("How many values?")
ok=[]
for x in range(0, int(num)):
ok.append(input())
print(ok)
And for nth value:
ans = ok[n-1]

How can I average several inputs?

I'm trying to code a calculator with several options, just for the leraning experience, and one of these options is 'average', I want the user to be able to input as many values as he wants to, but it's not working yet, what should I change?
This is my code for the average so far:
elif ui1 == subop1_2:
1 = [input("Input your values, separate with a comma").split(',')]
result = sum(1) / float(len(1))
print("The average is {}".format(result))
time.sleep(10)
Since there were a lot of things pointed out, here goes an answer.
num_list = input("Input your values, separate with a comma: ").split(',')
num_list = [float(elem) for elem in num_list]
result = sum(num_list) / float(len(num_list))
This will fail if the user enters an empty string or characters...
Every thing you wrote was perfectly fine except a few mistakes...
1) Change all 1s to a valid variable name. Lets say, a.
2) Remove the square brackets around the input() function
3) Add a this line before the line where you assign the variable, result.
a = [int(x) for x in a]
Here is the code,
a = input("Input your values, separate with a comma").split(',')
a = [int(x) for x in a]
result = sum(a) / float(len(a))
print("The average is {}".format(result))
first of all u cannot name a variable:1 change that to "a" or something and it should work out
I would do it like this:
inp = input("Input your values, separate with a comma")
values = list(map(float,inp.split(',')))
avg = sum(values)/len(values)
print("The average is {}".format(avg))

Comparing digits in a list to an integer, then returning the digits

I am using python version 3.
For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool).
The second part of the problem is to compare each individual element of the list to the average, then return the ones greater than the average.
I think the "if any" at the bottom will compare the numbers in the list to the Average, but I have no idea how to pull that value out to print it. You guys rock for all the help.
#Creating a list
my_numbers = [input("Enter a number: ") for i in range(5)]
#Finding sum
Total = sum(map(int, my_numbers))
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
if any in my_numbers > Average:
#Creating a list
my_numbers = []
r = range(5)
for i in r:
try:
my_numbers.append(int(input("Enter a number: ")))
except:
print( 'You must enter an integer' )
r.append(i)
#Finding sum
Total = sum(my_numbers)
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
print ([x for x in my_numbers if x>Average])
I'm sure that you would finally have succeeded in your code even if nobody hadn't answered.
My code is in fact to point out that you should foresee that entries could be non-integer and then to put instruction managing errors of entry.
The basic manner here is to use try except
Note the way I add i to r each time an error occurs in order to make up for the element of r that has been consumed.
Unfortunately, "if any" doesn't work. Take a look at the docs for the any function to se what it does. It doesn't do what you want even if your syntax had been correct. What you want is only the numbers greater than the average. You could use a list comprehension: [number for number in my_numbers if number > Average]. Or you could use a loop.
What you need to do is iterate through the list and print out the numbers above the average:
for i in my_numbers:
if int(i) > Average:
print(i)
To make things easier, you might also want to have the my_numbers list actually start out as a list of integers:
my_numbers = [int(input("Enter a number: ")) for i in range(5)]
Now we can get rid of the map function (don't worry, the hour did not go to waste, you'll find it very useful in other situations as well). You could also go straight to calculating the average without calculating the total, since you won't need the total again.
Average = sum(my_numbers) / 5
This means you can change the for loop so that you can replace int(i) with i.
You could also create a list with a list comprehension, and then print out the values in that list.
aboveAverage = [i for i in my_numbers if i > Average]
for i in aboveAverage:
print i

Categories

Resources