Parameter vs Argument Python

后端 未结 1 896
逝去的感伤
逝去的感伤 2021-02-13 20:43

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

相关标签:
1条回答
  • 2021-02-13 20:49

    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.

    0 讨论(0)
提交回复
热议问题