Python函数(二)

时间:2022-07-22
本文章向大家介绍Python函数(二),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

今天接着讲《像计算机科学家一样思考》第三章的习题

3.1. 编写一个能画出如下网格(grid)的函数:

# 执行两次
def do_twice(f):
    f()
    f()
    
# 执行四次
def do_four(f):
    do_twice(f)
    do_twice(f)

# 打印'+ - - - - '
def print_plus_dash():
    print('+ - - - - ', end='')
    
# 打印'|         '
def print_bar_space():
    print('|         ', end='')
    
# 打印两次'+ - - - - '
# 再打印一个'+'结尾
# 这个函数可以得到'+ - - - - + - - - - +'
def print_plus_row():
    do_twice(print_plus_dash)
    print('+')

# 打印两次'|         '
# 再打印一个'|'结尾
# 这个函数可以得到'|         |         |'
def print_bar_row():
    do_twice(print_bar_space)
    print('|')

#   打印一次'+ - - - - + - - - - +'
# 再打印四次'|         |         |'
# 可以得到'+ - - - - + - - - - +'
#        '|         |         |'
#        '|         |         |'
#        '|         |         |'
#        '|         |         |'
def print_plus_bar_rows():
    print_plus_row()
    do_four(print_bar_row)

# 打印两次
# '+ - - - - + - - - - +'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# 得到
# '+ - - - - + - - - - +'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# '+ - - - - + - - - - +'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# '|         |         |'
# 最后在打印一行
# '+ - - - - + - - - - +'
def print_grid():
    do_twice(print_plus_bar_rows)
    print_plus_row()

print('print plus row')
print_plus_row()
print('')

print('print bar row')
print_bar_row()
print('')

print('print plus bar rows')
print_plus_bar_rows()
print('')

print('print grid')
print_grid()

运行结果如下:

3.2编写一个能够画出四行四列的类似网格的函数。

def do_twice(f):
    f()
    f()

def do_four(f):
    do_twice(f)
    do_twice(f)

def print_plus_dash():
    print('+ - - - - ', end='')

def print_bar_space():
    print('|         ', end='')
    
# 因为要打印四行四列,所以这个地方需要将do_twice更换成do_four
def print_plus_row():
    do_four(print_plus_dash)
    print('+')
  
# 因为要打印四行四列,所以这个地方需要将do_twice更换成do_four
def print_bar_row():
    do_four(print_bar_space)
    print('|')
    
# 因为要打印四行四列,所以这个地方需要将do_twice更换成do_four
def print_plus_bar_rows():
    print_plus_row()
    do_four(print_bar_row)

# 因为要打印四行四列,所以这个地方需要将do_twice更换成do_four
def print_grid():
    do_four(print_plus_bar_rows)
    print_plus_row()

print('print plus row')
print_plus_row()
print('')

print('print bar row')
print_bar_row()
print('')

print('print plus bar rows')
print_plus_bar_rows()
print('')

print('print grid')
print_grid()

运行结果如下:

心得:

1. 感觉编程就像搭积木,每一块积木就像我们这里定义的一个函数。你可以想象你用乐高在拼一个汽车,那print_plus_row定义的这个函数可以看作是轮子,汽车有四个轮子,那将print_plus_row重复四次,汽车的所有轮子就都有了。

2. 编程是一个循序渐进的过程,一边写一边调试,一边看输出是不是你想要的东西。就像你搭积木,也是边搭边看说明书,看看搭出来的东西跟说明书上是不是一样的。

关于函数的简单介绍可以参考:Python函数(一)