简体   繁体   中英

What is the difference between a variable and a parameter

我是第一次学习 python 3 和一般编程,但我似乎无法区分参数和变量?

A parameter is a variable that was received as an argument to a function. Once the function has begun executing, the parameter is just like any other variable; it can be reassigned (and stops being tied to the caller's argument) like anything else.

 global_variable = ... still a variable, just defined globally ...
 def foo(parameter):
     function_local_variable = ... something defined locally ...


 foo(... argument that is bound to parameter in foo ...)

A variable is just something that refers/points to some data you have.

x = 5

Here x is a variable. Variables can point to more kinds of data than just numbers, though. They can point to strings, functions, etc.

A parameter is something that is passed into a function

def my_function(y):
    print(y)

Here y is a parameter. It doesn't contain a value yet. But if I want to call the function, I need to provide an argument to the function.

An argument is the actual value you provide to the function that replaces the parameter.

my_function(5)

Here, 5 is the argument. Of course, since x points to the value "5", I can do this too:

my_function(x)

which also prints 5

参数是一种变量,用作方法的输入。

A variable is a name (identifier) that refers to some value. Values can be either immutable types, that is, types that cannot be changed such as strings, bytes, integers and floating point numbers:

x = 5 # immutable type
y = x # y points to what x currently points to, namely 5
x = 9 # x points to a new value, 9
print(x, y) # 9 5

A variable can also name a mutable type:

class MyType:
    pass

t1 = MyType()
t1.x = 5 # set member x to 5
t2 = t1 # t2 points to the same object as t1
t1.x = 9
print(t1.x, t2.x) # 9 9

A parameter (or argument) is a value passed to a function:

def foo(x):
    print(x)

foo(some_value)

x is an argument to function foo . foo(some_value) invokes function foo with the value some_value as the actual value. The Python interpreter implicitly assigns x = some_value at the entry to function foo . Note that x is a variable is every sense of the word but that it is defined in the scope of foo so that it hides any other definition of x that may exist outside of foo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM