Creating Functions With Required Parameters
00:00 Defining Functions With Required Input Arguments. Instead of writing a shopping list directly in the code, you can now initialize an empty dictionary and write a function that allows you to add items to the shopping list.
00:44
The function iterates through the dictionary’s keys, and if the key exists, the quantity is increased. If the item is not one of the keys, the key is created, and a value of 1
is assigned to it.
00:58 You can run this script to show the printed dictionary.
01:07 You’ve included two parameters in the function signature: the item name and the quantity. The parameter names are used in the code within the function definition.
01:21 When you call the function, you pass arguments within the parentheses, one for each parameter. An argument is a value that you pass to the function. The distinction between parameters and arguments can often be overlooked.
01:36
It’s a subtle but important difference. You may sometimes find parameters referred to as formal parameters and arguments as actual parameters. The arguments you input when calling add_item()
are required arguments.
01:52 If you try to call the function without the arguments, you’ll get an error.
02:05
The traceback will give a TypeError
stating that the arguments are required. You’ll look at more error messages relating to using the wrong number of arguments or using them in the wrong order later on in this course.
02:20 But in the next section, you’ll see how to create more flexible functions by adding optional arguments.
Become a Member to join the conversation.