为了准备即将到来的考试,我一直在做一道巨蟒题。在网上搜索,试图找到类似的函数/文档来澄清问题后,我走到了死胡同。代码是遍历的,需要我们手动确定确切的输出。我发现很难解释函数到底在做什么,但实际上我已经运行了脚本,以便更仔细地查看是否可以清楚地了解情况。我能够确定为什么有些结果是这样的。
#!/usr/bin/python
y=5
def fun(i, x=[3,4,5], y=3):
print i, x,
y += 2
if y != 5:
print y,
print
return y
a = ["a", "b", "c", "d", "e", "f"]
a[1] = 'x'
fun(0)
fun(1, a)
a.append("x")
fun(2, a, 1)
fun(3, a[2:6])
fun(4, 4)
fun(5, a[:4])
fun(6, a[-3:-1])
s = "go python!"
fun(7, s)
fun(8, s[3:4])
fun(9, s[6])
fun(10, s)
fun(11, s[len(s)-1])
fun(12, s.split(" ")[1])
h = { "yes":2, 4:"no", 'maybe':5}
h['sortof'] = "6"
fun(13, h)
fun(14, h.keys())
h[0] = 4
h['never'] = 7
fun(15, h)
del( h[4] )
fun(16, h)
stooges = [ ["l", "c", "m"], 6, {'c':'d', 'e':'f'}, [ "x", "y"]]
fun(17, stooges)
fun(18, stooges[1])
fun(19, stooges[3][1])
print "20", fun(14, stooges[0][0], 7)输出如下所示。
0 [3, 4, 5]
1 ['a', 'x', 'c', 'd', 'e', 'f']
2 ['a', 'x', 'c', 'd', 'e', 'f', 'x'] 3
3 ['c', 'd', 'e', 'f']
4 4
5 ['a', 'x', 'c', 'd']
6 ['e', 'f']
7 go python!
8 p
9 h
10 go python!
11 !
12 python!
13 {'maybe': 5, 'yes': 2, 4: 'no', 'sortof': '6'}
14 ['maybe', 'yes', 4, 'sortof']
15 {0: 4, 4: 'no', 'maybe': 5, 'never': 7, 'sortof': '6', 'yes': 2}
16 {0: 4, 'maybe': 5, 'never': 7, 'sortof': '6', 'yes': 2}
17 [['l', 'c', 'm'], 6, {'c': 'd', 'e': 'f'}, ['x', 'y']]
18 6
19 y
20 14 l 9
9 当调用fun(0)时,我知道0只是传递给函数中的i,该函数打印i和x的值,结果是0 3,4,5。我还注意到,为了好玩( 1,a),它再次将1作为i传递给函数并打印1,但这次它不是打印x,而是打印a的值,这是一个用a[1]='x'...Basically更改的可变列表,为了切中要害,我不确定我是否确切地理解了函数中发生的事情,尽管研究输出使其更有意义。我真的很想为这样的问题做好准备,这样的问题肯定会在上面。到目前为止,仅仅因为这样一个问题,我做得很好的信心是相当低的,因为它将会值很多分。真的希望有人能帮助我,并解释这个函数是做什么的。本学期我们已经完成了自己的编程工作,但没有任何不切实际的地方。提前谢谢。
发布于 2014-12-09 09:32:56
在你的代码片段中发生了很多事情。因此,为了保持答案的一致性(并帮助您更好地学习),我建议使用Python调试器。使用调试器是您走向专业发展之路的关键。调试器会让你逐行检查代码,检查每一步的所有变量。这将帮助您了解变量是如何受每条语句影响的。我真的建议您使用调试器完成此练习。
为了让您开始了解以下内容:
import pdb # This is the Python debugger module. Comes with Python
y=5
def fun(i, x=[3,4,5], y=3):
print i, x,
y += 2
if y != 5:
print y,
print
return y
pdb.set_trace()
a = ["a", "b", "c", "d", "e", "f"]
a[1] = 'x'
fun(0)
fun(1, a)
a.append("x")
fun(2, a, 1) 现在运行此程序时,调试器将在执行a = ["a", "b", "c", "d", "e", "f"]之前等待您的输入。如果键入"s“并按enter,调试器将执行下一条语句。在任何时候,只需使用print命令来查看任何变量的值。Egs。在该步骤中,print a将向您显示a的值。有关更多选项,请参阅pdb docs。
希望这能在你的职业生涯中有所作为。
https://stackoverflow.com/questions/27369653
复制相似问题