Grak
Grak

Reputation: 99

How to handle a varying number of parameters on a function?

I'm trying to construct a code that gives a square's area and a rectangle's area with the same function, but I'm either running into missing positional argument error or something more exotic with whatever I do and I was flabbergasted by the potential solutions out there as I'm only a very basic level of python coder.

The biggest question is what kind of format should area() function be in order for me to be able to have it assume y is None if it's not given.

def area(x, y):
    return x * x if y is None else x * y #Calculate area for square and rectangle


def main(): 
    print("Square's area is {:.1f}".format(area(3))) #Square 
    print("Rectangle's area is {:.1f}".format(area(4, 3))) #Rectangle

main()

Upvotes: 0

Views: 36

Answers (1)

Bharel
Bharel

Reputation: 26900

Do it like so:

def area(x, y=None):
    return x * x if y is None else x * y #Calculate area for square and rectangle

By giving a default value, you may pass 1 less argument and it will be set to the default.

Upvotes: 1

Related Questions