2016-12-11 34 views
0

這個腳本作品在python2但不是在python3,輸入問題,仍然顯示,即使我把正確答案:得到工作,同時循環在python3

correct = "no" 
while correct == "no": 
    answer = input("15 x 17? ") 
    if answer == 15*17: 
     correct = "yes" 
     print 'good!' #for python2 
    else: 
     correct = "no" 

這可怎麼解決了這兩個不使用和使用函數?

回答

0

在Python 3 input返回一個字符串(在Python 2 input評估輸入),所以answer == 15*17,除非你轉換answer爲int或12*17字符串永遠不會爲真。

另外,print "good"不是有效的Python 3語法,因爲print是一個函數:print("good")

0

爲了使這項工作在兩個Py2.7和PY3有幾個語言版本之間的差異 - 見What’s New In Python 3.0

  • input()在PY3相當於raw_input()在PY2
  • print不再在PY3聲明,而是一個功能

要在兩個py2.7此代碼的工作和PY3你可以這樣做:

from __future__ import print_function 
try: 
    input = raw_input 
except NameError: 
    pass 

while True: 
    answer = int(input("15 x 17? ")) 
    if answer == 15*17: 
     print('good!') 
     break