-1

可能重复:
使用 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 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 的转换器。

谢谢你的帮助

4

1 回答 1

1

Python3 不再支持 print 作为一种特殊形式,其参数跟在 print 关键字后面(如print xPython 2.x 中一样)。相反print,现在是一个函数,需要一个参数列表,例如 in: print(x)请参阅http://docs.python.org/release/3.0.1/whatsnew/3.0.html中的“打印是一个函数”

此外,该break语句不能出现在循环之外。除Cswitch语句外,if不支持break。由于 if 语句没有贯穿逻辑,因此不需要它。为了停止执行函数并返回给调用者,请使用return.

代替is运算符,使用相等运算符==is测试对象是否相同,这是比相等更严格的测试。更多细节可以在这里找到。

此外,您将重量作为字符串。您可能希望使用函数将字符串转换为整数,以便与其他整数值进行比较int(weight)

还有一些其他的小错误:

  • e当您尝试w在函数调用中使用未定义的变量名称时,您正在为权重分配用户输入
  • 函数中的第一个参数被调用texture,但您textura在函数体中使用。
  • 您正在使用peso而不是weight在一个实例中

这是一个(不那么冒犯性的)重写,消除了这些错误:

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)
于 2012-10-20T13:30:30.023 回答