How to call a function with two arguments in python

后端 未结 3 1599
名媛妹妹
名媛妹妹 2021-01-29 15:48

i wanna ask about how to call a function with two arguments in python. for example,
code below is an example i want to call color function.

def color(objec         


        
相关标签:
3条回答
  • 2021-01-29 16:32

    The red variable is defined inside of color, so you can't use it outside of color.

    Instead, you have the variables tes and tes_2 defined, so the call to color should look like print color(tes, tes_2).

    0 讨论(0)
  • 2021-01-29 16:43

    The small but fundamental errors in your second block:

    1. Your arguments are object and arg2. objectis a reserved python word, both words are not so explanatory and (the real mistake) you never use arg2 in your function.
    2. You don't used any return value in the function.
    3. When you call the function, you use color(tes,red) when it should be color(tes,tes_2).

    I have rewritten the block, take a look (with some modifications you can fine-tune later)

    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
    

    An alternate suggestion to achieve what you want would be:

    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')
    

    EDIT: as requested (this is just the beginning ;oP . For example, you could use a dictionary of color names and color codes to call the function)

    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 讨论(0)
  • 2021-01-29 16:52
    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)
    

    I think you should visit Python2.7 Tutorial

    0 讨论(0)
提交回复
热议问题