按Enter键退出Python 3.4中的While循环

时间:2015-05-19 00:44:51

标签: python python-3.x while-loop exit-code

我是Python新手,过去几个月一直在教自己。我正在使用的书教授Python 2.7,而我正在尝试在3.4中学习Python。我已经习惯了现在都使用它们,但是对于我的生活,我无法弄清楚如何在使用回车键循环时退出。代码如下所示:

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)

我一直收到这个错误:

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

我能够在2.7中使用此代码的修改版本,但我想知道如何在3.4中执行此操作。我到处搜索,似乎找不到答案。

3 个答案:

答案 0 :(得分:3)

尝试使用此修正版的代码。你的逻辑是正确的,但你有一些错误。您不需要eval,在将数字添加到总数时必须将数字转换为integer,最后您必须在打印之前定义函数的平均值。

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))

<强>实施例

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.

答案 1 :(得分:2)

将用户的输入保持为字符串,直到您检查其内容:

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 + ".")

答案 2 :(得分:1)

我分开一个eval功能isNumber我让它保持浮动十进制,它似乎更清洁。

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)