Asset Classes

Free investment financial education

Language

Multilingual content from IBKR

Close Navigation
Learn more about IBKR accounts
Python Function Tutorial – Part VII

Python Function Tutorial – Part VII

Posted May 15, 2020 at 10:49 am
Jay Parmar
QuantInsti

See the previous installment in this series to catch up with Python functions with default arguments.

Python functions with variable length arguments

Let’s consider a scenario where we as developers aren’t sure about how many arguments a user will want to pass while calling a python function. For example, a function that takes floats or integers (irrespective of how many they are) as arguments and returns the sum of all of them. We can implement this scenario as shown below:

def sum_all(*args):
“””Sum all values in the *args.”””
# Initialize result to 0
result = 0
# Sum all values
for i in args:
result += i
# Return the result
return result

The flexible argument is written as * followed by the parameter name in the Python function definition. The parameter args preceded by * denotes that this parameter is of variable length. Python then unpacks it to a tuple of the same name args which will be available to use within the function. In the above example, we initialize the variable result to 0 which will hold the sum of all arguments. We then loop over the args to compute a sum and update the result with each iteration. Finally, we return the sum to the calling statement. The sum_all python function can be called with any number of arguments and it will add them all up as follows:

# Calling the sum_all function with arbitrary number of arguments.
print(sum_all(1, 2, 3, 4, 5))
# Output
15
# Calling with different numbers of arguments.
print(sum_all(15, 20, 6))
# Output
41

Here, *args is used as the parameter name (the shorthand for arguments), but we can use any valid identifier as the parameter name. It justs needs to be preceded by * to make it flexible in length. On the same lines, Python provides another flavor of flexible arguments which are preceded by double asterisk marks. When used ,they are unpacked to dictionaries (with the same name) by the interpreter and are available to use within the function. For example:

def info(**kwargs):
“””Print out key-value pairs in **kwargs.”””
# Run for loop to prints dictionary items
for key, value in kwargs.items():
print(key + ‘: ‘ + value)

Here, the parameter **kwargs are known as keywords arguments which will be converted into a dictionary of the same name. We then loop over it and print all keys and values. Again, it is totally valid to use an identifier other than kwargs as the parameter name. The info python function can be called as follows:

# Calling the function
print(info(ticker=’AAPL’, price=’146.83′, name=’Apple Inc.’, country=’US’))
# Output
ticker: AAPL
price: 146.83
name: Apple Inc.
country: US

That is all about the default and flexible arguments.

In the next installment, the author will discuss documentation string, DocStrings.

Visit https://www.quantinsti.com/ for ready-to-use Python functions as applied in trading and data analysis.

Disclosure: Interactive Brokers

Information posted on IBKR Campus that is provided by third-parties does NOT constitute a recommendation that you should contract for the services of that third party. Third-party participants who contribute to IBKR Campus are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from QuantInsti and is being posted with its permission. The views expressed in this material are solely those of the author and/or QuantInsti and Interactive Brokers is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to buy or sell any security. It should not be construed as research or investment advice or a recommendation to buy, sell or hold any security or commodity. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

IBKR Campus Newsletters

This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.