Press Enter to exit the loop in Python 3.4
I am new to Python and have been learning for the past few months. The book I am using teaches Python 2.7 while I am trying to learn Python in 3.4. I'm used to using both now, but for the life of me, I can't figure out how to exit the while loop with the enter key. The code is displayed 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 can get a modified version of this code to work in 2.7, but I would like to know how to do it in 3.4. I have searched everywhere and cannot find an answer.
source to share
Try this corrected version of your code. Your logic is correct, but you got a few bugs. You didn't need to eval
, you needed to convert the number to integer
by adding it to the grand total, and finally you needed to determine the average outside 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))
<strong> 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.
source to share
Keep the user as a string until you check its content:
total = 0
count = 0
while 1:
data = input("Enter a number or press enter to quit: ")
try:
data = float(data)
except ValueError:
break
count += 1
total += data
average = total / count
print("The sum is " + total ". The average is " + average + ".")
source to share
I share the eval funtion isNumber I force it to store decimal numbers and it seems a little cleaner.
def isNumber(value):
try:
float(value)
return True
except ValueError:
"error"
return False
total = 0
count = 0
data = input("Enter a number or press enter to quit: ")
while data and isNumber(data):
count += 1
number = float(data)
total += number
average = total / count #This sentences is more clean here (for me)
data = input("Enter a number or press enter to quit: ")
print("The sum is", total, ". ", "The average is", average)
source to share