我想问一下如何在 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
你能告诉我如何在 python 中制作一个功能良好的程序吗?蒂
第二个块中的小但基本的错误:
- 你的论点是
object
and arg2
. object
是一个保留的Python单词,这两个词都没有那么解释性并且(真正的错误)你从来没有使用过arg2
在你的函数中。
- 你没有使用过任何
return
函数中的值。
- 当您调用该函数时,您使用
color(tes,red)
当它应该是color(tes,tes_2)
.
我已经重写了块,你看一下(有一些修改,你可以稍后微调)
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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)