So I'm still pretty new to Python and I am still confused about using a parameter vs an argument. For example, how would I write a function that accepts a string as an argument?
Argument: A value passed to a function (or method) when calling the function. Parameter: A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept. Python doesn't really have "variables" like some other languages - it has "names" referring to "objects".
In the below example, name, age, and skill are the parameters as they appear in the function definition. Arguments are the names that appear in the function call. In the above example, ‘Chetan’, 33, and ‘Python’ are the arguments as they appear when making a call to the function my_func. There are two types of arguments.
Arguments The arguments are the variables given to the function for execution. Besides, the local variables of the function take the values of the arguments and therefore can process these parameters for the final output. Now, let’s look at the function calling in the pseudocode above.
Hence Python won't allow passing the values as keyword arguments. Python’s built-in function len () makes use of positional-only parameter as you can see the function definition in the below screenshot. Keyword-only parameters indicate that arguments can only be passed to function by keywords.
Generally when people say parameter/argument they mean the same thing, but the main difference between them is that the parameter is what is declared in the function, while an argument is what is passed through when calling the function.
def add(a, b): return a+b add(5, 4)
Here, the parameters are a
and b
, and the arguments being passed through are 5
and 4
.
Since Python is a dynamically typed language, we do not need to declare the types of the parameters when declaring a function (unlike in other languages such as C). Thus, we can not control what exact type is passed through as an argument to the function. For example, in the above function, we could do add("hello", "hi")
.
This is where functions such as isinstance()
are helpful because they can determine the type of an object. For example, if you do isinstance("hello", int)
, it will return False since "hello"
is a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With