为了准备考试,我一直在研究一个python问题。在网上搜索试图找到类似的功能/文档来清理之后,我已经走到了尽头。代码是通过要求我们手动确定确切的输出。我发现很难解释函数正在做什么,但实际上已经运行脚本以仔细查看是否清楚事情。我能够确定为什么有些结果是他们的样子。
#!/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'
...基本上为了达到目的,我不确定我是否完全理解函数中发生了什么,虽然研究输出使它更有意义,我真的我想参加为这样一个问题准备的考试,这个考试肯定会在这个问题上进行。到目前为止,我仅仅因为这样的问题而表现良好的信心非常低,因为它值得花很多时间。真的希望有人可以帮助我解释这个功能正在做什么。我们已经完成了本学期的编程工作,但没有什么不切实际的。提前谢谢。
答案 0 :(得分:1)
您的代码段中发生了很多事情。所以为了保持答案(并帮助你更好地学习),我建议使用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”并输入,调试器将执行下一个语句。在任何时候,只需使用print
命令查看任何变量的值。 EGS。 print a
会在此步骤显示a
的值。有关更多选项,请参阅pdb docs。
希望这会在你职业生涯的某个地方产生影响。