我知道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转换器。
感谢您的帮助
答案 0 :(得分:1)
Python3不再支持print作为特殊形式,其参数位于print关键字后面(如Python 2.x中的print x
)。
相反,print
现在是一个函数,需要一个参数列表,如:
print(x)
。请参阅http://docs.python.org/release/3.0.1/whatsnew/3.0.html
此外,break
语句不能在循环外发生。除了C switch
语句之外,if
不支持break。因为if语句没有直接逻辑,所以不需要它。为了停止执行该函数并返回给调用者,请使用return
。
使用等于运算符is
而不是==
运算符。 is
测试对象是否相同,这是一个比平等更严格的测试。
可以找到更多详细信息here。
此外,你将体重作为一个字符串。您可能希望使用函数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)