3️⃣

11.3 Parameters

Parameters

Functions have parameters, which are used to generalize what the function does. You can also think of the parameters as inputs to the function.

For example, I could have a function called scoop_ice_cream(flavor), which has a parameter called flavor. Parameters, as you can see, are placed inside the parentheses after the name of the function.

When I call or use the method, I pass in an argument for flavor (the actual value that goes into the parameter), such as ‘vanilla’ or ‘chocolate’. To call the function, I would type scoop_ice_cream('vanilla') or scoop_ice_cream('chocolate').

This is useful because I don’t have to retype a bunch of code that’s associated with scooping ice cream, I can use the same code with different flavors!

def scoop_ice_cream(flavor):
	if flavor == "chocolate":
		print("That will be $2!")
	elif flavor == "vanilla":
		print("That will be $1!")
	else:
		print("That will be $3!")

scoop_ice_cream("chocolate")

Output:

That will be $2!

Multiple Parameters

You can have as many parameters as you want. You can also have no parameters. For example, print() can take no parameters, and it will simply output an empty line.

However, if you do decide to have multiple parameters, remember that the order of how you input your parameters matters. In the example below, since 5 is the first argument given, it gets assigned to the first parameter, which is a.

def func(a, b, c):
	print("a is " + a)
	print("b is " + b)
	print("c is " + c)

func(5, 6, 7)

Output:

a is 5
b is 6
c is 7

Keyword and Default Parameters

Using keyword parameters is a way to inputting values into a function without having to worry about the order. Here is an example of its use:

def func(p1, p2, p3):
	print(p1)
  print(p2)
  print(p3)

func(p3=1, p1=2, p2=3)

Output:

2
3
1

Another use for these keywords is setting default values for certain parameters. Here is an example of this:

def car(speed=100):  # if no speed is given, 100 is the default value
  print("Car speed:", speed)

car(speed=150)  # prints "Car speed: 150"
car()  # prints "Car speed: 100"

Special Parameters

There are also special parameters on top of the ones previously mentioned. These are the *args and **kwargs arguments.

*args

*args is used to take in an unknown number of regular parameters into a function. With the use of typical parameters, there must be a set number of arguments given to a certain function. However, by using the *args special parameter, any number of parameters can be inputted, as long as it is inputted correctly. This special argument will store its provided data into a tuple, which acts similarly to a list, except that it cannot be changed (it is immutable). For a more detailed description of tuples, see

def function_name(param1, *args):
	print(param1)  # prints "p1"
  print(args)  # prints (1, 2, 3, 4)
	print(args[0])  # prints 1

function_name("p1", 1, 2, 3, 4)
💡

Note that "args" is just an arbitrary phrase. You can replace it with another name, like *arguments, as long as you have * in front.

💡

If no parameters are passed to *args, then args will be an empty tuple.

**kwargs

**kwargs is used to take an unknown number of keyword arguments into a function. Like the *args function, using this type of parameter makes setting arguments beforehand not necessary. This argument will store a dictionary of the keyword arguments provided, where the keyword is the key and the data of the parameter is the value.

def function_name(param1, **kwargs):
	print(param1)  # prints "p1"
  print(kwargs)  # prints {"a":1, "b":2, "c":3}

function_name("p1", a=1, b=2, c=3)
💡

Note that, like *args, "kwargs" is an arbitrary name. You can use any name with this special parameter, as long as you have ** in front. An example could be **keywordargs.

💡

If no parameters are passed to **kwargs, then kwargs will be an empty dictionary.

*args and keyword parameters in use

If you have an editor like repl.it or VSCode, then you can inspect the print function. This provides a good example of the use of *args. You'll notice that, when inspected, the print function has the parameter *values. This allows for you to print multiple objects in the same print function, as detailed below.

name = "John Doe"
print("hi there", name + ".", "How are you?")
# in this case, values = ("hi there", "John Doe.", "How are you?)
# so "hi there John Doe. How are you?" is printed
# Because print takes *values instead of just values, you can print
# as many objects as you want, or as few as you want, in just one print call.

You'll also remember from previous lessons that print has a keyword parameter end that determines what character to print after the provided values. This is a great example of a keyword parameter since, by default, end is set to \n, but it can be specified in the function call.

print("hi", end=" ")  # since we specified it, end = " "
print("there")  # since we didn't specify it, end is it's default value, "\n"
print("bob")

Output:

hi there
bob

**kwargs in use

Suppose we want to write a function that outputs a stylized (like italicized or underlined) message on Discord, but we don't want to have individual keyword arguments for each style. This is where **kwargs could come in handy. Check out the example below.

def stylized_print(message, **kwargs):
    """
    While this doesn't actually print stylized messages to the console,
    it still provides what you would type if you wanted a stylized message
    on a platform like notion or discord
    """
    if "italicized" in kwargs and kwargs["italicized"] is True:
        message = "*" + message + "*"
    if "underlined" in kwargs and kwargs["underlined"] is True:
        message = "__" + message + "__"
    print(message)

stylized_print("hello")
# kwargs = {}
# since neither underlined nor italicized was provided, only "hello" is printed

stylized_print("hi there", italicized = True)
# kwargs = {"italicized": True}
# since just italicized is provided and italicized is True, "*hi there*" is printed

stylized_print("cool", underlined = True)
# kwargs = {"underlined": True}
# will print "__cool__" because underlined was specified

stylized_print("underlined italicized", underlined = True, italicized = True)
# kwargs = {"underlined": True, "italicized": True}
# will print "__*underlined italicized*__"
⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.