2014-09-03 193 views
-1

这是肯·兰伯特的“Python的基础”:这是为什么不打印

{ 
sum=0 
while True: 
    data = input('enter a number or just enter to quit: ') 
    if data == "": 
     break 
    number = float(data) 
    sum += number 
print("the sum is", sum) 
} 

错误消息:

data = input('enter a number or just enter to quit: ') 
    File "<string>", line 0 

    ^
SyntaxError: unexpected EOF while parsing 

Process finished with exit code 1 
+3

你不把周围的代码块的大括号在Python。 – Barmar 2014-09-03 19:34:16

+0

我删除了它们,它们仍然没有打印 – kits 2014-09-03 19:35:35

+0

现在不能看到“输入数字或只是输入以退出:”吗? (打印) – 2014-09-03 19:36:58

回答

0

您提供的错误是因为你使用的输入,其试图执行来自stdin的文本为python代码https://docs.python.org/2/library/functions.html#input。我在下面提供了一些修复。

sum=0 
while True: 
    data = raw_input('enter a number or just enter to quit: ') 
    if len(data) < 1: 
     break 
    number = float(data) 
    sum += number 
print("the sum is %f" % sum) 
+0

也可能值得放一个'try /除了ValueError'循环。但是,如果用户希望继续使用不良的用户输入,那么这取决于用户的偏好。 – 2014-09-03 19:45:14

+0

同意,但我为简单起见(并将验证保留给OP) – user590028 2014-09-03 19:45:57

+2

混合的空白将产生'IndentationError',而不是'SyntaxError'。 – chepner 2014-09-03 19:46:29

1

Use raw_input rather than input. The description ofinput开始:

Equivalent to eval(raw_input(prompt))

你得到一个错误,因为eval("")报告一个语法错误,因为没有表达中;它立即得到EOF。

在另一方面,raw_input描述说:

The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

由于您希望用户键入,而不是表达的评价字符串,这是你应该使用的函数。

+0

可能值得注意的是,示例代码是针对Python 3.x的,而OP则是在Python 2.x解释器中运行它。 – chepner 2014-09-03 19:50:18

+0

是的,这是正确的我正在使用2.x.并感谢Barmar! – kits 2014-09-03 19:51:50

0

我发现你的代码有语法问题。如果你想要把数据在一个变量,你应该使用:

variable = raw_input("Please enter ____") 

因此,你应该更换4号线:

data = raw_input('enter a number or just enter to quit: ')