Search code examples
pythoniterationcharacteraverage

How to stop a loop when i press a button in python


In the code in the follow lines is tried to implement an average calculator which calculate the average of given numbers with the division of the sum of given numbers through the count of multitude of them. The problem is that when is pressed the S button does not break the loop which count the multitude of numbers count. In addition, it is preferable to have the line which ask the numbers and the letter which stop the procedure in one line

import itertools
total=0
numbers=[]
for i in itertools.count(1):
    numbers.append (input ("Enter number:")))
    print("You give" , i)
    s=str(input("If you want to stop press S:"))
    #i = i + 1
    s=False
    if s is True:
        break
        total=sum(numbers)/i
        print ("                            ")
        print ("                            ")
        print ("Average is", total)

Solution

  • Try this:

    import itertools
    total=0
    numbers=[]
    
    for i in itertools.count(1):
        numbers.append(int(input ("Enter number:")))
    
        print("You give" , i)
    
        s=str(input("If you want to stop press S:"))
        if s.lower() == "s":
            total = sum(numbers)/i
            print ("                            ")
            print ("                            ")
            print ("Average is", total)
            break