在python中运行函数后是否更改了变量?

kin*_*ing -1 python python-2.7

所以我从我正在阅读的书中写了这个函数,这就是它的开始:

def cheese_and_crackers(cheese_count, boxes_of_crackers):
    print "You have %d cheeses!" % cheese_count
    print "You have %d boxes of crackers!" % boxes_of_crackers
    print "Man that's enough for a party!"
    print "Get a blanket.\n"
Run Code Online (Sandbox Code Playgroud)

好的,有道理.然后,这是当这个函数运行的时候,我有点困惑,并想确认一些事情:

print "OR, we can use variables from our script:"
amount_of_cheese = 10
amount_of_crackers = 50  

cheese_and_crackers(amount_of_cheese, amount_of_crackers)
Run Code Online (Sandbox Code Playgroud)

让我困惑的是,amount_of_cheese和amount_of_crackers正在改变变量(verbage?不确定我说的是正确的术语)来自cheese_count和boxes_of_crackers,分别来自函数中的第一个初始变量标签.

所以我的问题是,当你使用的是与你编写的初始函数中使用的变量不同的变量时,为什么要更改你写出新变量名后的名字呢?如果新变量显示在新变量之后,程序将如何知道它们是什么?

我认为python从上到下读取程序,还是从头到尾读取?

那有意义吗?我不确定如何解释它.感谢您的任何帮助.:)(python 2.7)

sam*_*hen 6

我认为你对参数传递的命名规则感到有点困惑.

考虑:

def foo(a, b):
    print a
    print b
Run Code Online (Sandbox Code Playgroud)

你可以打电话foo如下:

x = 1
y = 2
foo(x, y)
Run Code Online (Sandbox Code Playgroud)

你会看到:

1
2
Run Code Online (Sandbox Code Playgroud)

a, b函数签名(函数定义的第1行)中arguments()的变量名称不必与调用函数时使用的实际变量名称一致.

当你打电话时,把它想象成这样:

foo(x, y)
Run Code Online (Sandbox Code Playgroud)

它说:"调用函数foo;传入xas a,传入yb".此外,这里的参数作为副本传递,因此如果您要在函数内部修改它们,它将不会更改函数外部的值,也不会更改它的调用位置.考虑以下:

def bar(a, b):
    a = a + 1
    b = b + 2
    print a

x = 0
y = 0
bar(x, y)
print x
print y
Run Code Online (Sandbox Code Playgroud)

你会看到:

1
2
0
0
Run Code Online (Sandbox Code Playgroud)