2012-10-20 17 views
-1

可能重複語法錯誤:
Syntax error on print with Python 3與基本的Python 3發行

我知道Python的應該是解釋型語言...它的簡單性的神,它缺少冗餘, 等等等等等等。但由於我太習慣C,C++,Java,Javascript和Php,我必須承認這很煩人。這裏是我的代碼:

#!/usr/bin/python3.1 
def shit(texture, weight): 
    if textura is "green": 
     texturaTxt = "Shit is green" 
    elif textura is "blue": 
     texturaTxt = "Shit is blue" 
    elif textura is "purple": 
     texturaTxt = "Shit is purple" 
    else: 
     print "Incorrect color" 
     break 
    if weight < 20: 
     pesoTxt = " and weights so few" 
    elif weight >= 20 and peso <=50: 
     pesoTxt = " and weights mid" 
    elif weight > 50: 
     pesoTxt = " and weights a damn lot" 
    else: 
     print "Incorrect weight" 
    return texturaTxt + pesoTxt 

c = input("Introduce crappy color: ") 
e = input("Introduce stupid weight: ") 
r = shit(c, w) 
print r 

我努力學習Python和我試圖實現是:

... 
function shit(texture, weight) { 
    string textureTxt = "Shit is ", pesoTxt = " and weights "; 
    switch(texture) { 
     case "green": textureTxt .= "green as an applee"; break; 
     case "blue": textureTxt .= "blue as the sky"; break; 
     case "purple": textureTxt .= "purple as fucking Barny"; break; 
     default: cout<<"Incorrect texture, try again later" <<endl; exit; 
    } 
    //etc 
} 
string color = ""; 
int weight = 0; 
cout<<"Introduce color: "; 
cin>>color; 
//etc 
cout<<shit(color, weight); 
... 

但我放棄了,我不能讓它工作,它拋出我的所有類型的錯誤。希望有一些C++或PHP或C到Python轉換器那裏。

感謝您的幫助

+1

使用'印刷(R) – kev

回答

1

Python3不再支持打印與打印的關鍵字(如在Python 2.x的print x)以下參數的一種特殊形式。 而不是print現在是一個功能,並需要一個參數列表如下: print(x)。請參閱「打印是函數」中的http://docs.python.org/release/3.0.1/whatsnew/3.0.html

此外,break語句不能出現在循環之外。除C switch聲明外,if不支持中斷。由於if語句沒有貫穿邏輯,所以不需要。爲了停止執行該功能並返回給調用者使用return

而不是is運算符,使用相等運算符==is測試對象是否相同,這是一個比平等更嚴格的測試。 更多細節見here

此外,你正在獲得作爲一個字符串的重量。您可能需要使用函數int(weight)將字符串轉換爲整數,以便與其他整數值進行比較。

此外還有一些其他的小錯誤:

  • 當你嘗試在函數調用中使用未定義的變量名w您分配了權重的用戶輸入e
  • 第一函數中的參數稱爲texture,但在函數體中使用textura
  • 您在一個實例

這裏使用peso代替weight是(較少的進攻)與消除這些錯誤改寫:`在PY3

def stuff(color, weight): 

    color_txt = "Your stuff is " 
    if color == "green": 
     color_txt += "green as an apple" 
    elif color == "blue": 
     color_txt += "blue as the sky" 
    elif color == "purple": 
     color_txt += "purple as an eggplant" 
    else: 
     print("Invalid color!") 
     return 

    w = 0 
    # converting a string to an integer might 
    # throw an exception if the input is invalid 
    try: 
     w = int(weight) 
    except ValueError: 
     print("Invalid weight!") 
     return 

    weight_txt = "" 
    if w<20: 
     weight_txt = " and weighs so few" 
    elif 20 <= w <= 50: 
     weight_txt = " and weighs mid" 
    elif w > 50: 
     weight_txt = " and weighs a lot" 
    else: 
     print("Invalid weight!") 

    return color_txt + weight_txt 

c = input("Input color: ") 
w = input("Input weight: ") 
r = stuff(c, w) 
print(r)