繁体   English   中英

Python函数演练

[英]Python function walkthrough

我一直在研究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]。 我还注意到,对于fun(1,a),它再次将1传递给函数i并输出1,但是这次而不是输出x,而是输出a的值,这是一个可变的列表,用a[1]='x'进行a[1]='x'更改...基本上来说,我不确定我确切地了解函数中发生了什么,尽管研究输出使它更有意义,但我真的很想参加该考试,以准备一个肯定会出现的问题。 到目前为止,仅仅因为这样的问题,我对表现良好的信心就很低,因为它将获得很多成绩。 真希望有人能帮助我并解释该功能的作用。 本学期我们已经完成了编程工作,但是没有什么不切实际的。 提前致谢。

您的代码段中发生了很多事情。 因此,为了保持答案的简洁性(并帮助您更好地学习),我建议使用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文档

希望这对您的职业有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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