2012-03-10 104 views
-4

我想问一下如何在python中调用带有两个参数的函数。例如,
下面的代码是我想调用颜色函数的一个示例。如何在Python中调用带有两个参数的函数

def color(object): 
    return '\033[1;34m'+object+'\033[1;m' 
tes = 'this must be blue' 
print color(tes) 

但这仅仅是一个参数。 然后我想用不同的颜色选择两个参数。 下面是我的虚拟代码。

def color(object,arg2): 
    blue = '\033[1;34m'+object+'\033[1;m' 
    red = '\033[1;31m'+object+'\033[1;m' 
tes = 'this must be blue' 
tes_2 = 'i wanna this string into red!!' 
print color(tes,red) 

很好,这只是我的虚拟代码和这将是类似这样的错误..

print color(tes,red) 
NameError: name 'red' is not defined 

你能告诉我如何在蟒蛇一个运行良好的? TY

+1

写'red ='而不是'tes_2 =' – 2012-03-10 15:45:09

+0

你真的想要'color(arg1,arg2)'返回什么? – 2012-03-10 15:51:08

+0

取决于我定义了一个新的变量。 只是出来的颜色可以用两个参数来调用。已经在函数中定义了。 – user1070579 2012-03-10 15:53:55

回答

2

小,但根本的错误,在你的第二块:

  1. 你的论点是objectarg2object是一个保留的python单词,这两个单词都不是如此解释性的(真正的错误),您从不在函数中使用arg2
  2. 您在函数中没有使用任何return值。
  3. 当您调用该函数时,当它应该是color(tes,tes_2)时,使用color(tes,red)

我已经重写了该块,看看(有一些修改,你可以微调后)

def color(color1,color2): 
    blue = '\033[1;34m'+color1+'\033[1;m' 
    red = '\033[1;31m'+color2+'\033[1;m' 
    return blue, red 

tes = 'this must be blue' 
tes_2 = 'i wanna this string into red!!' 
for c in color(tes,tes_2): 
    print c 

其他建议,以达到你想要将是什么:

def to_blue(color): 
    return '\033[1;34m'+color+'\033[1;m' 

def to_red(color): 
    return '\033[1;31m'+color+'\033[1;m' 

print to_blue('this is blue') 
print to_red('now this is red') 

编辑:根据要求(这只是开始; oP。例如,您可以使用颜色名称和颜色代码字典来调用该功能)

def to_color(string, color): 
    if color == "blue": 
     return '\033[1;34m'+color+'\033[1;m' 
    elif color == "red": 
     return '\033[1;31m'+color+'\033[1;m' 
    else: 
     return "Are you kidding?" 
     #should be 'raise some error etc etc.' 

print to_color("this blue", "blue") 
print to_color("this red", "red") 
print to_color("his yellow", "yellow") 
+0

如何根据我们想要指定的内容调用函数? def color(object,第二个参数指定我们想要的颜色,例如:红色): ty – user1070579 2012-03-10 15:59:22

+0

非常有帮助,谢谢! – user1070579 2012-03-10 16:26:07

1
def color(object,arg2): 
    blue = '\033[1;34m'+object+'\033[1;m' 
    red = '\033[1;31m'+arg2+'\033[1;m' 
    return blue + red 
tes = 'this must be blue' 
tes_2 = 'i wanna this string into red!!' 
print color(tes,tes_2) 

,我认为你应该去参观Python2.7 Tutorial

+0

请不要使用对象作为变量名称,它是内置的。 – root 2013-01-09 10:13:58

1

red变量的color中定义的,所以你不能用它的color之外。

相反,你有变量tes和定义tes_2,所以调用color应该像print color(tes, tes_2)

相关问题