Search code examples
pythonlistloopssum

Program calculating sum, min, max values of user input


As the title says, I have created a program that does the following until the user presses the 'X' key. Which then stops and prints out all values in order. I also would like to mention that I can only use a specific compiler through my university, which registers the program as an error/wrong even though it should be correct.

Edit: Added the Status of the compiler. Compiler

My question is, what other alternatives can I use to code a similar program, or any recommendations in general.

The requested input:

1

2

X

The requested output:

result:[1, 2]

average:1.50

min:1.00

max:2.00

Screenshot of running program

list1 = []
asknumber = str(0)
while asknumber != 'X':
  asknumber = input("Enter number: ")
  if asknumber == 'X':
    break
  list1.append(int(asknumber))
  big_value = max(list1)
  min_value = min(list1)
  average = sum(list1) / len(list1)
print("result:", sorted(list1))
print("average:", f'{average:.2f}')
print("min:", f'{min_value:.2f}')
print("max:", f'{big_value:.2f}')

Solution

  • Since a computer is grading your work, the error is likely because you have spaces after your colons.

    Someone suggested to use the following to resolve that issue:

    print("result:", sorted(list1), sep='')
    

    However, since you are already using f strings in your print statement, you might as well use them for all of it.

    You also do not need to calculate the min, max, and average until the loop ends—and since you break the loop manually, you can just use while True:.

    list1 = []
    asknumber = str(0)
    while True:
        asknumber = input("Enter number: ")
        if asknumber == 'X':
            break
        list1.append(int(asknumber))
    big_value = max(list1)
    min_value = min(list1)
    average = sum(list1) / len(list1)
    print(f'result:{sorted(list1)}')
    print(f'average:{average:.2f}')
    print(f'min:{min_value:.2f}')
    print(f'max:{big_value:.2f}')