Home > OS >  TypeError: function() missing 1 required positional argument: 'y'
TypeError: function() missing 1 required positional argument: 'y'

Time:11-20

I want the greet function to say "Hi Sam, Hi Cody" using the format function but I am getting this error:

greet(names())
TypeError: greet() missing 1 required positional argument: 'y' 



def names():
        def name1():
            x = "Sam"
            return x
        def name2():
            y = "Cody"
            return y 

What do I need to put in greet(names()) to get this to work?

from names import names

def greet(x,y):
    template = "Hi {}, Hi {} ".format(x,y)
    print(template)


greet(names())

CodePudding user response:

Is this what you're after:

def name1():
    return 'Sam'

def name2():
    return 'Cody'

def greet (x, y):
    print (f'Hi {x}, Hi {y}')
    
greet (name1(), name2())

# Result:
    # Hi Sam, Hi Cody

names() returning multiple outputs

If you wanted to write a single function names() that returns multiple outputs, you can do it like this:

def names():
    return 'Sam', 'Cody'

The return from names() is a tuple containing two strings. If you pass it directly to greet(), you'll be passing greet() a single argument - a tuple that happens to contain two things within it. That will produce the error you were getting:

greet (names())

TypeError: greet() missing 1 required positional argument: 'y'

You could, on the other hand, unpack the tuple returned by names() when you pass it to greet(), like so:

greet (*names())
# Result:
    # Hi Sam, Hi Cody
  • Related