Posted on

Learn Python Episode #19: Infinite Arguments

Get The Learn to Code Course Bundle!
https://josephdelgadillo.com/product/learn-to-code-course-bundle/

Enroll in The Complete Python Course on Udemy!
https://www.udemy.com/python-complete/?couponCode=PYTHONWP

In this video we are going to discuss passing an infinite number of arguments in to a function. So, let’s go ahead and write a function.

def print_people(*people):

So, here we have a function called print_people, and the asterisk tells this argument that it’s going to be an array of all the arguments that are passed in to the function. This may result in 1, 100, 1,000, etc. arguments, and we will see how this works in a moment. With an array we need some way to loop over it, and so we’re going to be using a for statement.

for person in people:
print("This person is", person)

Basically, the for loop allows us to iterate over the people list and pass the values into our function as arguments. Again, if you’re familiar with other programming languages this is not a new concept, it’s just a slightly different way of doing it. Let’s call the print_people function and pass it some names.

print_people("Nick", "Dan", "Jack", "King", "Smiley")

What we’re doing here is passing 5 arguments. Now if we knew we were always going to expect 5 arguments, we could accept each individual argument as it’s own variable. However, if we don’t know the total number of values, we are going to create an array stored in the variable called people. So, that’s how to include an infinite, or flexible, number of parameters. In the next tutorial we will cover return values.

Web – https://josephdelgadillo.com/
Subscribe – https://goo.gl/tkaGgy
Follow for Updates – https://steemit.com/@jo3potato