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?
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.
See the FAQ:
What is the difference between arguments and parameters?
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs): pass
foo, bar and kwargs are parameters of
func
. However, when callingfunc
, for example:func(42, bar=314, extra=somevar)
the values
42
,314
, andsomevar
are arguments.
See also:
- language-agnostic What's the difference between an argument and a parameter?
- This answer is my favourite.
For defining a function that accepts a string, see TerryA's answer. I just want to mention that you can add type hints to help people using your function to tell what types it accepts, as well as what type it returns.
def greeting(name: str) -> str:
return 'Hello ' + name
In Programming lingo, arguments refers to the data you are passing to the function that is being called whereas the parameter is the name of the data and we use the parameter inside the function to refer it and do things with it.
for example:
def functionname(something):
do some stuff with {something}
functionname(abc)
in this case,
abc
--> argumentsomething
--> parameter
A parameter is the placeholder; an argument is what holds the place.
Parameters are conceptual; arguments are actual.
Parameters are the function-call signatures defined at compile-time; Arguments are the values passed at run-time.
Mnemonic: "Pee" for Placeholder Parameters, "Aeigh" for Actual Arguments.
© 2022 - 2024 — McMap. All rights reserved.