Variable number of arguments with one or more fixed arguments

Lesson Details:
June 29, 2020

I: Introduction

A: What is a programming language?

Programming languages are used to write and read programs and codes. Some programming languages are more powerful than others and can be used to write complex programs and codes. Python is one of the most popular beginner friendly programming languages. It’s easy to learn and use. It’s both readable and writable.

II: Body

A: Variable number of arguments with one or more fixed arguments

A variable number of arguments is a function that accepts any number of arguments as long as they are of the same type.

For example, we could create a function that adds together every item in a list using a variable number of arguments:

def add_all ( * args ): total = 0 for i in args: total += i return total

The *args argument is a placeholder for any number of arguments we wish to pass into the function. Here we pass in exactly one argument, a list of numbers:

add_all ( 1 , 2 , 3 ) #=> 6

2. Fixed arguments with optional arguments

We can also use the *args variable to accept any number of arguments, but also to specify an optional argument.

For example, let’s create a function that takes in two arguments, the first being an integer, and the second being a string. The function will return the integer plus the string, like so:

def add ( n , s = "" ): if s == "" : return n + s else : return n + s + "!"

Note that when we call this function, we pass an empty string into the second argument, which makes the function behave like this:

add ( 1 ) #=> 1 add ( 1 , "!" ) #=> 1!

But if we want to pass in a string, we can do so like this:

add ( 2 , "yay" ) #=> 3

III: Conclusion

Course content