Write a program to read a list of non-negative integers,

and to display the largest integer, the smallest integer,

and the average of all the integers.

The user indicates the end of the list by entering a negative

sentinel value (use -1) that is NOT used in the calculations.

The average should be displayed as a value of type float,

to three decimal places.

The program should repeat at the user's request.

This is code that I have typed in so far, but I dun know to use it beyond that, please help.

max_number = -1
min_number = 10000000
total = 0
list_of_numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
list_of_numbers = int (list_of_numbers)
while list_of_numbers != -1:
list_of_numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
list_of_numbers = int (list_of_numbers)

Thanks,

Tony

## All 9 Replies

To start, list_of_numbers is not a list of numbers but an integer. Or,
list_of_numbers = int (list_of_numbers)
will throw an error because you can not convert a list, and there would be no need for a while loop either. Most people who see
list_of_numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
would enter a list of numbers, i.e. 1,2,3

Your next step is to store each input number in a list. Then it becomes fairly simple; total the numbers in the list and calculate the average. For the max and min, you can either traverse the list and find the max and min, or test each number as it is input and store in variables if they are the largest or smallest so far.

Hi, this is the new code I tried, but it still does not work, any suggestions?

max_number = -1
min_number = 100000000
list = 0
numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
numbers = int (numbers)
while numbers != -1:
total = numbers + max_number
total = numbers + min_number
list = list + 1
numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
numbers = int (numbers)
if total > max_number:
print (numbers)
if total < min_number:
print (numbers)

Hi, this is the new code I tried, but it still does not work, any suggestions?

max_number = -1
min_number = 100000000
list = 0
numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
numbers = int (numbers)
while numbers != -1:
total = numbers + max_number
total = numbers + min_number
list = list + 1
numbers = (input("Enter a list of numbers, (Enter -1 to stop): "))
numbers = int (numbers)
if total > max_number:
print (numbers)
if total < min_number:
print (numbers)

Try something like this:

``````def number_thing():
print("Type numbers one by one as prompted, and type -1 to end it")
numbers = []
while True:
while True:
n = input("Type another number")
try:
n = int(n)
except ValueError:
print("Invalid, need to be a number.")
else:
break
if n == -1:
break
numbers.append(n)
numbers.sort()
the_sum = 0
for n in numbers:
the_sum += n
print("Greatest:", numbers[-1], "  Least:", numbers, "Average:", the_sum / len(numbers))
if __name__ == "__main__":
while True:
number_thing()
if 'y' in input("again? (y/n)"):
pass
else:
break``````

I'll explain it all to you: `def number_thing():` This is the function that does everything. `print("Type numbers one by one as prompted, and type -1 to end it")` - This is just giving the user the instructions. `numbers = []` - We're creating an empty list here, and it will contain all the numbers. I'll explain this next bit with comments (# comment...):

``````while True: # This loops and repeatedly asks the user to enter
# another number
while True: # This asks the user to enter a number,
# and keeps doing it until they enter a
# valid number it will tell the to try again
# if they enter for example "n", that's a string.
n = input("Type another number") # store's the number they
# type in variable n.
try:                           # This tries to do something
n = int(n)              # It tries to convert n to a number (int)
except ValueError:    # But if there is a ValueError while
# trying (This is the error you get
# when you do this: int("")
print("Invalid, need to be a number.") # Tell them it's not
# a number
else:              # If there was no error, stop looping (break)
break
# If there was an error, it will loop again asking for a number
# Now that the number has been chosen and it is a valid int,
#Check if it is -1
if n == -1:  # If the number is -1, stop looping (break)
break
# If it was -1 and stopped looping, it won't get added to the list
# because it won't get this far because it stopped looping
numbers.append(n) # Add the number to the list``````

Now, `numbers.sort()` - This sorts the list of numbers, from least to greatest. It is a list function. `the_sum = 0` - This will be the sum of all the numbers in the numbers list. It will be used to get the average.

``````for n in numbers:
the_sum += n``````

This goes through the numbers list and adds each number to the_sum. `print("Greatest:", numbers[-1], " Least:", numbers, "Average:", the_sum / len(numbers))` - The greatest number is numbers[-1]. The -1 index means the last element in the list, and since we sorted the list, that means the last one is the greatest. The least is numbers, the first element since we've sorted the list, the first one is least. The average is the_sum divided by the amount of numbers - len(numbers).

``````if __name__ == "__main__": # The __name__ is equal to __main__
# When the script is run. So when you
# run the .py file, __name__ will be
# equal to "__main__", and this part
# will be executed (ran).
while True:                    # Loops, running the number_thing()
# function until the user doesnt wan't to
# anymore
number_thing()  # do the function
if 'y' in input("again? (y/n)"): # if the letter y is in the input
# (they said yes),
pass  # Do nothing (it will keep looping and do the function
# again).
else:       # if the user didn't say yes, stop looping.
break``````

Thats it. I hope this helped and you understand it all.Feel free to ask any questions.
-MK12

To read in a list of integers with a loop you have to create an empty list and append to it with each input. For instance:

``````# create a list of integers
# note that input() gives a string in Python3

n_list = []
while True:
n = int(input("Enter a positive integer (-1 to quit): "))
n_list.append(n)
if n < 0:
break

print(n_list)

"""
my example output -->
[33, 12, 123, 567, -1]
"""``````

I left the end marker -1 in the list. If you break before the append then the -1 is omitted.

If you leave the -1 of the list or remove it, then you can just use:

``````low_number = min(n_list)
high_number = max(n_list)
total = sum(n_list)
average = float(total)/len(n_list)``````

However, your instructor, being rather tricky, most likely wants you to take care of the -1 as you do your calculations.

Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.

[code=python]

[/code]

Try something like this:

``````def number_thing():
print("Type numbers one by one as prompted, and type -1 to end it")
numbers = []
while True:
while True:
n = input("Type another number")
try:
n = int(n)
except ValueError:
print("Invalid, need to be a number.")
else:
break
if n == -1:
break
numbers.append(n)
numbers.sort()
the_sum = 0
for n in numbers:
the_sum += n
print("Greatest:", numbers[-1], "  Least:", numbers, "Average:", the_sum / len(numbers))
if __name__ == "__main__":
while True:
number_thing()
if 'y' in input("again? (y/n)"):
pass
else:
break``````

I'll explain it all to you: `def number_thing():` This is the function that does everything. `print("Type numbers one by one as prompted, and type -1 to end it")` - This is just giving the user the instructions. `numbers = []` - We're creating an empty list here, and it will contain all the numbers. I'll explain this next bit with comments (# comment...):

``````while True: # This loops and repeatedly asks the user to enter
# another number
while True: # This asks the user to enter a number,
# and keeps doing it until they enter a
# valid number it will tell the to try again
# if they enter for example "n", that's a string.
n = input("Type another number") # store's the number they
# type in variable n.
try:                           # This tries to do something
n = int(n)              # It tries to convert n to a number (int)
except ValueError:    # But if there is a ValueError while
# trying (This is the error you get
# when you do this: int("")
print("Invalid, need to be a number.") # Tell them it's not
# a number
else:              # If there was no error, stop looping (break)
break
# If there was an error, it will loop again asking for a number
# Now that the number has been chosen and it is a valid int,
#Check if it is -1
if n == -1:  # If the number is -1, stop looping (break)
break
# If it was -1 and stopped looping, it won't get added to the list
# because it won't get this far because it stopped looping
numbers.append(n) # Add the number to the list``````

Now, `numbers.sort()` - This sorts the list of numbers, from least to greatest. It is a list function. `the_sum = 0` - This will be the sum of all the numbers in the numbers list. It will be used to get the average.

``````for n in numbers:
the_sum += n``````

This goes through the numbers list and adds each number to the_sum. `print("Greatest:", numbers[-1], " Least:", numbers, "Average:", the_sum / len(numbers))` - The greatest number is numbers[-1]. The -1 index means the last element in the list, and since we sorted the list, that means the last one is the greatest. The least is numbers, the first element since we've sorted the list, the first one is least. The average is the_sum divided by the amount of numbers - len(numbers).

``````if __name__ == "__main__": # The __name__ is equal to __main__
# When the script is run. So when you
# run the .py file, __name__ will be
# equal to "__main__", and this part
# will be executed (ran).
while True:                    # Loops, running the number_thing()
# function until the user doesnt wan't to
# anymore
number_thing()  # do the function
if 'y' in input("again? (y/n)"): # if the letter y is in the input
# (they said yes),
pass  # Do nothing (it will keep looping and do the function
# again).
else:       # if the user didn't say yes, stop looping.
break``````

Thats it. I hope this helped and you understand it all.Feel free to ask any questions.
-MK12

Thank you so much, I managed to figure it out and it work perfectly...

Tony

To read in a list of integers with a loop you have to create an empty list and append to it with each input. For instance:

``````# create a list of integers
# note that input() gives a string in Python3

n_list = []
while True:
n = int(input("Enter a positive integer (-1 to quit): "))
n_list.append(n)
if n < 0:
break

print(n_list)

"""
my example output -->
[33, 12, 123, 567, -1]
"""``````

I left the end marker -1 in the list. If you break before the append then the -1 is omitted.

If you leave the -1 of the list or remove it, then you can just use:

``````low_number = min(n_list)
high_number = max(n_list)
total = sum(n_list)
average = float(total)/len(n_list)``````

However, your instructor, being rather tricky, most likely wants you to take care of the -1 as you do your calculations.

Please use code tags with your code to preserve the indentations. Otherwise the code is very difficult to read and not too many folks will help.

[code=python]

[/code]

Tony

Thanks to everyone for their valuable advice and help in solving my assignment, thanks a million guys, appreciate it...

Tony

You understand what I showed you right? You didn't just copy and paste that and hand it in without figuring out what it does right?

You understand what I showed you right? You didn't just copy and paste that and hand it in without figuring out what it does right?

Don't worry, I understood what you told me and then I typed in the code to make the program work, I did not copy and paste, I just used you code as a guideline, but, it was good because you explained everything very clearly and I was able to comprehend how the program should work....

Thanks again,

Tony

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.