Python程序设计(第三版)课后题答案 第六章 [约翰·策勒 (著) 人民邮电出版社]

Python程序设计(第三版)课后题答案 第六章

编程练习题

  • 1.编写一个程序来打印歌曲“Old MacDonald”的歌词。你的程序应该打印五种不同动物的歌词,类似于下下面的例子。
    Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
    And on that farm he had a cow, Ee-igh,Ee-igh,Oh!
    With a moo,moo here and a moo,moo there.
    Here a moo, there a moo, everywhere a moo,moo.
    Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
    答案
def lyrics(animal, cry):
    for i in range(len(animal)):
        print('Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!')
        print('And on that farm he had a {0}, Ee-igh,Ee-igh,Oh!'.format(animal[i]))
        print('With a {0},{0} here and a {0},{0} there.'.format(cry[i]))
        print('Here a {0}, there a {0}, everywhere a {0},{0}.'.format(cry[i]))
        print('Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!\n')


def print_lyrics():  # 打印歌词Old MacDonald
    animal = ['cow', 'dog', 'cat', 'pig', 'sheep']
    sound = ['moo', 'wang', 'miao', 'heng', 'mie']
    lyrics(animal, sound)


print_lyrics()

输出结果:

Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
And on that farm he had a cow, Ee-igh,Ee-igh,Oh!
With a moo,moo here and a moo,moo there.
Here a moo, there a moo, everywhere a moo,moo.
Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!

Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
And on that farm he had a dog, Ee-igh,Ee-igh,Oh!
With a wang,wang here and a wang,wang there.
Here a wang, there a wang, everywhere a wang,wang.
Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!

Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
And on that farm he had a cat, Ee-igh,Ee-igh,Oh!
With a miao,miao here and a miao,miao there.
Here a miao, there a miao, everywhere a miao,miao.
Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!

Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
And on that farm he had a pig, Ee-igh,Ee-igh,Oh!
With a heng,heng here and a heng,heng there.
Here a heng, there a heng, everywhere a heng,heng.
Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!

Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!
And on that farm he had a sheep, Ee-igh,Ee-igh,Oh!
With a mie,mie here and a mie,mie there.
Here a mie, there a mie, everywhere a mie,mie.
Old MacDonald had a farm,Ee-igh,Ee-igh,Oh!


进程已结束,退出代码0
  • 2.写一个程序来打印“The Ants Go Marching.”十段的歌词。下面给出几个例句。你可以为每一节中的“little one”选择你自己的活动,但一定要选择一些押韵的内容。
    The ants go marching one by one,hurrah! hurrah!
    The ants go marching one by one,hurrah! hurrah!
    The ants go marching one by one,
    The little one stops to suck his thumb,
    And they all go marching down…
    In the ground…
    To get out …
    Of the rain.
    Boom! Boom! Boom!
    The ants go marching two by two,hurrah! hurrah!
    The ants go marching two by two,hurrah! hurrah!
    The ants go marching two by two,
    The little one stops to suck his shoes,
    And they all go marching down…
    In the ground…
    To get out …
    Of the rain.
    Boom! Boom! Boom!

答案

def lyrics2(count, limbs):
    for i in range(len(count)):
        print('The ants go marching {0} by {0},hurrah! hurrah!\nThe ants go marching {0} by {0},hurrah! hurrah!\nThe '
              'ants go marching {0} by {0},\nThe little one stops to suck his {1},\nAnd they all go marching '
              'down...\nIn the ground...\nTo get out ...\nOf the rain.\nBoom! Boom!  Boom! \n'.format(count[i], limbs[i]))


def print_lyrics():  # 打印歌词The ants go marching
    number = ['one', 'two', 'three']
    body = ['thumb', 'shoe', 'arm']
    lyrics2(number, body)


print_lyrics()

输出结果:

The ants go marching one by one,hurrah! hurrah!
The ants go marching one by one,hurrah! hurrah!
The ants go marching one by one,
The little one stops to suck his thumb,
And they all go marching down...
In the ground...
To get out ...
Of the rain.
Boom! Boom!  Boom! 

The ants go marching two by two,hurrah! hurrah!
The ants go marching two by two,hurrah! hurrah!
The ants go marching two by two,
The little one stops to suck his shoe,
And they all go marching down...
In the ground...
To get out ...
Of the rain.
Boom! Boom!  Boom! 

The ants go marching three by three,hurrah! hurrah!
The ants go marching three by three,hurrah! hurrah!
The ants go marching three by three,
The little one stops to suck his arm,
And they all go marching down...
In the ground...
To get out ...
Of the rain.
Boom! Boom!  Boom! 


进程已结束,退出代码0
  • 3.写出这些函数的定义:
    sphereArea(radius)返回具有给定半径的球体的表面积。
    sphereVolume(radius)返回具有给定半径的球体的体积。
    使用你的函数来解决第三章中的编程练习1.
    答案
def sphereArea(radius):
    return 4 * pi * radius ** 2


def sphereVolume(radius):
    return 4 / 3 * pi * radius ** 3


def calculate():
    r = eval(input("请输入球体的半径:"))
    a = sphereArea(r)
    v = sphereVolume(r)
    print("球体的表面积是:{0:0.2f},体积是:{1:0.2f}".format(a, v))


calculate()

输出如下:

请输入球体的半径:6
球体的表面积是:452.39,体积是:904.78

进程已结束,退出代码0
  • 4.写出一下两个函数的定义:
    sumN(n)返回前n个自然数的和。
    sumNCubes(n)返回前n个自然数的立方和的总和。
    然后在提示用户输入n的程序中使用这些函数,并打印前n个自然数的和与前n个自然数的立方之和。
    答案
def sumN(n):  # 返回前n个自然数的和
    sum = 0
    for i in range(n):
        sum = sum + i
    return sum


def sumNCubes(n):  # 返回前n个自然数的立方和的总和
    sum = 0
    for i in range(n):
        sum = sum + i ** 3
    return sum


def summation():
    n = eval(input("请输入要计算的n值:"))
    s1 = sumN(n)
    s2 = sumNCubes(n)
    print("前{0}自然数的和是:{1},立方和是:{2}".format(n, s1, s2))


summation()

输出如下:

请输入要计算的n值:55个自然数的和是:10,立方和是:100

进程已结束,退出代码0
  • 5.第3章的重做编程练习2。使用两个函数:一个计算比萨饼的面积,一个计算每平方英寸的成本。
    答案
def area(diameter):  # 返回披萨的面积
    return pi * (diameter / 2)**2


def tprice(area, price):  # 返回披萨的成本
    return price * area


def pizza():
    diameter, price = eval(input("请输入披萨的直径和单价:"))
    a = area(diameter)
    print("披萨的最终成本是:{0:0.2f}".format(tprice(a, price)))


pizza()

输出结果如下:

请输入披萨的直径和单价:7,8
披萨的最终成本是:307.88

进程已结束,退出代码0
  • 6.编写一个函数,给定三边的长度作为参数,计算三角形的面积。使用你的函数增强本章中的triangle2.py让它也显示三角形的面积。
    答案
    给定长度计算面积的程序:
def calculat_area(a, b, c):  # 给定三边长,求三角形面积
    s = (a + b + c) / 2
    area = sqrt(s * (s - a) * (s - b) * (s - c))
    return area


def triangular_area():
    s1, s2, s3 = eval(input("请输入三角形的三个边长:"))
    print('三角形的面积是:{0:0.2f}'.format(calculat_area(s1, s2, s3)))


triangular_area()

输出结果如下:

请输入三角形的三个边长:4,5,6
三角形的面积是:9.92

进程已结束,退出代码0

增强triangle2.py后的程序如下:

def square(x):
    return x * x


def distance(p1, p2):
    dist = math.sqrt(square(p2.getX() - p1.getX())
                     + square(p2.getY() - p1.getY()))
    return dist

#  添加的函数部分
def calculat_area(a, b, c):  # 给定三边长,求三角形面积  
    s = (a + b + c) / 2
    area = math.sqrt(s * (s - a) * (s - b) * (s - c))
    return area

def main():
    win = GraphWin("Draw a Triangle", 300, 300)
    win.setCoords(0.0, 0.0, 10.0, 10.0)
    message1 = Text(Point(5, 0.5), "Click on three points")
    message1.draw(win)

    # Get and draw three vertices of triangle
    p1 = win.getMouse()
    p1.draw(win)
    p2 = win.getMouse()
    p2.draw(win)
    p3 = win.getMouse()
    p3.draw(win)

    # Use Polygon object to draw the triangle
    triangle = Polygon(p1, p2, p3)
    triangle.setFill("peachpuff")
    triangle.setOutline("cyan")
    triangle.draw(win)

    # Calculate the perimeter of the triangle
    perim = distance(p1, p2) + distance(p2, p3) + distance(p3, p1)
    area = calculat_area(distance(p1, p2), distance(p2, p3), distance(p3, p1))   #  添加的语句
    message1.setText("The perimeter is: {0:0.2f},the area is:{1:0.2f}".format(perim, area))   # 修改的语句

    # Wait for another click to exit
    win.getMouse()
    win.close()


main()

输出如图所示:
在这里插入图片描述

  • 7.编写一个函数来计算第n个斐波那契数列。用你的函数来解决第三章中的编程练习16.
    答案:
def fibonacci(n):
    a, b = 1, 1
    for i in range(n - 1):
        a, b = b, a + b
    return a


def cal_fibonacci():
    n = eval(input('请输入要计算第几位斐波那契数列:'))
    print('第{0}位斐波那契数列的值为:{1}'.format(n, fibonacci(n)))


cal_fibonacci()

输出结果如下:

请输入要计算第几位斐波那契数列:88位斐波那契数列的值为:21

进程已结束,退出代码0
  • 8.用返回下一个猜测的函数nextGuess(guess,x)解决第3章中的编程练习17.
    答案:
def nextGuess(guess, x):
    return (guess + x / guess) / 2


def guess_sqrt():  # 猜测平方根的值
    x = float(input("请输入要计算平方根的数:"))
    n = int(input("请输入改进猜测的次数:"))
    guess = x / 2
    for i in range(n):
        guess = nextGuess(guess, x)

    f = sqrt(x) - guess

    print("计算的猜测值的结果为:", guess)
    print("猜测值与实际值的差值为:", f)


guess_sqrt()

输出结果如下:

请输入要计算平方根的数:10
请输入改进猜测的次数:10
计算的猜测值的结果为: 3.162277660168379
猜测值与实际值的差值为: 4.440892098500626e-16

进程已结束,退出代码0
  • 9.用返回分数的字母等级的函数grade(score)完成第5章的编程练习3.
    答案:
def grade(score):
    m = score // 10
    levelist = ['F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A']
    return levelist[m]


def main():  # 测验100分制成绩等级转换
    g = int(input("Enter you grade number(0~100): "))
    print("测验成绩等级为:", grade(g))


main()

输出结果如下:

Enter you grade number(0~100): 92
测验成绩等级为: A

进程已结束,退出代码0
  • 10.用函数acronym(phrase)完成第5章的编程练习4,该函数返回字符串短语的首字母缩略词。
    答案:
def acronym(phrase):
    acronym = ''  # 定义缩略语为空
    for word in phrase.split():
        acronym = acronym + word[0]  # 取分割后单词的首字母连接成新的字符串
    return acronym.upper()


def main():  # 提取短语首字母
    phrase = input("Enter a phrase: ")
    print("The abbreviation of the phrase is:", acronym(phrase))  # 将构造的字符串全部大写


main()

输出结果如下:

Enter a phrase: It will be a fine day tomorrow
The abbreviation of the phrase is: IWBAFDT

进程已结束,退出代码0
  • 11.编写并测试一个函数,满足以下规格说明。
    squareEach(nums),nums是一个数字列表。修改列表,对每一项平方。
    答案:
def squareEach(nums):
    for i in range(len(nums)):
        nums[i] = nums[i] ** 2
    # return nums


def main():
    numlist = eval(input('请输入一个数字列表:'))
    squareEach(numlist)
    print('平方后的序列为:', numlist)


main()

输出结果如下:

请输入一个数字序列:[1,2,3,4]
平方后的序列为: [1, 4, 9, 16]

进程已结束,退出代码0
  • 12.编写并测试一个函数,满足以下规格说明。
    sumList(nums)nums是一个数字列表。返回列表中数字的和。
    答案:
def sumList(nums):
    sum = 0
    for i in range(len(nums)):
        sum = sum + nums[i]
    return sum


def main():
    numlist = eval(input('请输入一个数字列表:'))
    print('数字列表求和的结果为:', sumList(numlist))


main()

输出结果如下:

请输入一个数字列表:[1,2,3,4]
数字列表求和的结果为: 10

进程已结束,退出代码0
  • 13.编写并测试一个函数,满足以下规格说明。
    toNumbers(strList)strList是一个字符串列表,每个字符串表示一个数字。修改列表,将每一项转换为数字。
    答案:
def toNumbers(strList):
    for i in range(len(strList)):
        if strList[i].isdigit():
             strList[i] = int(strList[i])
        else:
             strList[i] = float(strList[i])
    return strList


def main():
    strlist = eval(input('请输入一个字符串列表:'))
    print('字符串列表转换为数字的结果:', toNumbers(strlist))


main()

输出结果如下:

请输入一个字符串列表:['1', '2.3', '4', '5.6']
字符串列表转换为数字的结果: [1, 2.3, 4, 5.6]

进程已结束,退出代码0
  • 14.使用前面三个问题中的函数来实现计算从文件读取的数字的平方和的程序。你的程序应提示输入文件名,并打印出文件中值的平方和。(提示:使用readlines().)
    答案:
def squareEach(nums):
    for i in range(len(nums)):
        nums[i] = nums[i] ** 2


def sumList(nums):
    sum = 0
    for i in range(len(nums)):
        sum = sum + nums[i]
    return sum


def toNumbers(strList):
    for i in range(len(strList)):
        if strList[i].isdigit():
            strList[i] = int(strList[i])
        else:
            strList[i] = float(strList[i])
    return strList


def main():
    fname = input('请输入要计算的文件名:')
    infile = open(fname, "r")
    numlist = infile.readlines()
    a = toNumbers(numlist)
    squareEach(a)
    sum = sumList(a)
    print('文件中数字的平方和为:', sum)


main()

文件内容如下:
在这里插入图片描述

输出结果如下:

请输入要计算的文件名:infile6.txt
文件中数字的平方和为: 64.0

进程已结束,退出代码0
  • 15.编写并测试一个函数,满足以下规模说明。
  • drawFace(center,size,win)center是一个Point,size是一个int,win是一个GraphWin.在win中绘制一张给定尺寸的简单的脸。
    你的函数可以画一个简单的笑脸(或严峻的脸)。编写一个在单个窗口中绘制不同大小的几张脸的程序,来演示该函数。
    答案:
def drawFace(cente, size, win):
    x = int(cente.getX())
    y = int(cente.getY())
    r = int(size)
    # 绘制脸
    face = Circle(Point(x, y), r)
    face.setFill("peachpuff")
    face.draw(win)

    # 绘制左眼
    eye_left = Circle(Point(x-r/3, y+r/3), r/5)
    eye_left.setFill("white")
    eye_left.draw(win)

    # 绘制右眼
    eye_right = Circle(Point(x+r/3, y+r/3), r/5)
    eye_right.setFill("white")
    eye_right.draw(win)

    # 绘制鼻子
    nose = Rectangle(Point(x-r/16, y-r/12), Point(x+r/16, y-r/6))
    nose.setFill("black")
    nose.draw(win)

    # 绘制嘴巴
    mouth = Rectangle(Point(x-r/8, y-r/2), Point(x+r/8, y-r/3))
    mouth.setFill("red")
    mouth.draw(win)



def main():
    win = GraphWin("面孔", 600, 600)
    win.setCoords(0.0, 0.0, 100.0, 100.0)  # 将图像坐标统一为宽窄为100的方块
    win.setBackground("white")
    t = Text(Point(50, 8), "Please click to generate face")
    t.draw(win)
    n = eval(input('请输入你想绘制几个笑脸:'))
    for i in range(n):
        print('绘制你的第{0}个笑脸,'.format(i+1), end='')
        r = input("请设置半径为:")
        p = win.getMouse()
        drawFace(p, r, win)

    print('再次点击图像退出程序!')
    win.getMouse()
    win.close()


main()

输出结果如下所示:
在这里插入图片描述

请输入你想绘制几个笑脸:3
绘制你的第1个笑脸,请设置半径为:5
绘制你的第2个笑脸,请设置半径为:15
绘制你的第3个笑脸,请设置半径为:20
再次点击图像退出程序!

进程已结束,退出代码0
  • 16.使用上一个练习中的drawFace函数来编写照片匿名程序。此程序允许用户加载图像文件(例如PPM或GIF),并在照片中已有的脸上绘制卡通脸。用户首先输入包含图像的文件的名称。显示图像,并询问用户要遮挡多少脸。然后程序进入一个循环,供用户点击每个脸的两个点:中心和脸边缘上的某处(以确定脸的大小)。然后程序应使用drawFace函数在该位置绘制一个脸。
    (提示:第四章中描述了图形库中的图像处理方法。将图像居中显示在GraphWin中,窗口的大小与图像相同,并将图形绘制到此窗口中。你可以使用屏幕捕获工具程序保存生成的图像。)
    答案:
def drawFace(center, size, win):
    x = int(center.getX())
    y = int(center.getY())
    r = int(size)
    # 绘制脸
    face = Circle(Point(x, y), r)
    face.setFill("peachpuff")
    face.draw(win)

    # 绘制左眼
    eye_left = Circle(Point(x - r / 3, y + r / 3), r / 5)
    eye_left.setFill("white")
    eye_left.draw(win)

    # 绘制右眼
    eye_right = Circle(Point(x + r / 3, y + r / 3), r / 5)
    eye_right.setFill("white")
    eye_right.draw(win)

    # 绘制鼻子
    nose = Rectangle(Point(x - r / 16, y - r / 12), Point(x + r / 16, y - r / 6))
    nose.setFill("black")
    nose.draw(win)

    # 绘制嘴巴
    mouth = Rectangle(Point(x - r / 8, y - r / 2), Point(x + r / 8, y - r / 3))
    mouth.setFill("red")
    mouth.draw(win)

def main():
    fname = input('请输入图像的文件名:')
    win = GraphWin("图像", 600, 600)
    win.setCoords(0.0, 0.0, 100.0, 100.0)  # 将图像坐标统一为宽窄为100的方块
    win.setBackground("white")

    picture = Image(Point(50, 50), fname)
    picture.draw(win)

    n = eval(input('请输入需要遮挡几张脸?:'))
    for i in range(n):
        c = win.getMouse()
        p = win.getMouse()
        r = sqrt((p.getX()-c.getX())**2 + (p.getY()-c.getY())**2)
        drawFace(c, r, win)

    win.getMouse()
    win.close()


main()

输出图像如图:
[外链图片转存中…(img-Iorxb5so-1719571568337)]

请输入图像的文件名:team.png
请输入需要遮挡几张脸?:2

进程已结束,退出代码0
  • 17.写一个函数,满足以下规格说明。
    moveTo(shape,newCenter)shape是一个支持getCenter方法的图形对象,newCenter是一个点。移动形状,使newCenter成为其中心。
    用你的函数编写一个绘制圆圈的程序,然后允许用户单击窗口10次。每次用户点击时,圆圈都会移动到用户点击的位置。
    答案:
def moveTo(shape, newCenter):
    sp = shape.getCenter()
    cp = newCenter
    dx = cp.getX() - sp.getX()
    dy = cp.getY() - sp.getY()
    shape.move(dx, dy)


def main():
    win = GraphWin("移动图像", 600, 600)
    win.setCoords(0.0, 0.0, 100.0, 100.0)  # 将图像坐标统一为宽窄为100的方块
    win.setBackground("white")

    p = win.getMouse()
    phase = Circle(p, 8)
    phase.setFill('pink')
    phase.draw(win)

    for i in range(10):
        newp = win.getMouse()
        moveTo(phase, newp)


main()

输出结果如图:移动鼠标位置点击,圆圈跟随鼠标移动。
在这里插入图片描述








如有错误,请读者批评指正!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值