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 :/
CodePudding user response:
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):
Appendingstring
of the number instead ofint
. 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 usesum()
to get the total of a list. list.sort()
will sort the list andprint(list.sort())
would lead toNone
because it just sorts the list and doesn't return anything. To print sorted list usesorted(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.