Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter vs Argument Python

Tags:

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?

like image 683
svlk Avatar asked Nov 07 '17 23:11

svlk


People also ask

What is the difference between an argument and a parameter?

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".

What are the parameters and arguments in Python?

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.

What is an argument in a function?

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.

How to pass values as keyword arguments in Python's Len() function?

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.


1 Answers

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.

like image 184
TerryA Avatar answered Oct 06 '22 00:10

TerryA