2012-03-10 103 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)

相關問題