Search code examples
pythonpython-3.xwhile-loopexit-code

Press Enter to exit While Loop in Python 3.4


I am new to Python and have been teaching myself over the past few months. The book I am using teaches Python 2.7, while I am trying to learn Python in 3.4. I've become accustomed to using both now, but for the life of me I can't figure out how to exit this while loop with the enter key. The code appears below:

total = 0
count = 0
data = eval(input("Enter a number or press enter to quit: "))

while data != "":
    count += 1
    number = data
    total += number
    average = total / count
    data = eval(input("Enter a number or press enter to quit: "))
print("The sum is", total, ". ", "The average is", average)

I keep getting this error:

Traceback (most recent call last):
  File "/Users/Tay/Documents/Count & Average.py", line 10, in <module>
    data = eval(input("Enter a number or press enter to quit: "))
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing

I am able to get a modified version of this code to work in 2.7, but I would like to know how to do this in 3.4. I've searched around everywhere and can't seem to find an answer.


Solution

  • Try this corrected version of your code. Your logic is correct, but you had a few errors. You don't need eval, you had to convert the number to an integer when adding it to the total, and finally you had to define average outside of the function before you printed it out.

    total = 0
    count = 0
    average = 0
    data = input("Enter a number or press enter to quit: ")
    
    while data:
        count += 1
        number = data
        total += int(number)
        average = total / count
        data = input("Enter a number or press enter to quit: ")
    
    print("The sum is {0}. The average is {1}.".format(total, average))
    

    Examples:

    Enter a number or press enter to quit: 5
    Enter a number or press enter to quit: 4
    Enter a number or press enter to quit: 3
    Enter a number or press enter to quit: 2
    Enter a number or press enter to quit: 
    The sum is 14. The average is 3.5.
    
    Enter a number or press enter to quit: 
    The sum is 0. The average is 0.