2014-09-03 188 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: ')