Python核心编程第二版答案17


前言

Python核心编程第二版是Python语言学习的权威指南,全面介绍了Python的语法、特性和用途。本文将提供该书的答案,帮助读者解决练习和巩固知识。

第1章 Python初步
练习1.1:无
练习1.2:无

第2章 数据类型和操作符
练习2.1:大
练习2.2:True
练习2.3:270

第3章 控制流
练习3.1:

if x % 2 == 0:
print("偶数")
else:
print("奇数")


练习3.2:

while x > 0:
x = x // 10
if x % 10 == 3:
print("包含3")
break



第4章 函数
练习4.1:

def sum_digits(n):
"""求整数n各数位之和"""
sum = 0
while n > 0:
sum += n % 10
n = n // 10
return sum


练习4.2:

def is_palindrome(s):
"""判断字符串s是否为回文"""
return s == s[::-1]



第5章 数据结构:列表和元组
练习5.1:['a', 'b', 'c', 1, 2, 3]
练习5.2:('a', 'b', 'c', 1, 2, 3)

第6章 数据结构:字典和集合
练习6.1:

d = {'name': 'Alice', 'age': 25, 'city': 'New York'}


练习6.2:

s = set(['a', 'b', 'c', 1, 2, 3])



第7章 对象和类
练习7.1:

class Person:
def __init__(self, name, age):
= name
= age
def say_hello(self):
print("Hello, my name is {} and I am {} years old".format(, ))


练习7.2:

p1 = Person("Alice", 25)
p1.say_hello() # 输出:Hello, my name is Alice and I am 25 years old



第8章 文件和异常
练习8.1:

with open("", "w") as f:
("Hello world!")


练习8.2:

try:
open("", "r")
except FileNotFoundError:
print("文件不存在")



第9章 模块和包
练习9.1:

import math
print() # 输出:3.141592653589793


练习9.2:

from PIL import Image
image = ("")



第10章 面向对象的编程
练习10.1:

class Animal:
def __init__(self, name):
= name
class Dog(Animal):
def speak(self):
print("汪汪")
d = Dog("旺财")
() # 输出:汪汪


练习10.2:

class Restaurant:
def __init__(self, name, menu):
= name
= menu
def add_item(self, item, price):
[item] = price
def print_menu(self):
for item, price in ():
print(f"{item}: ${price}")
r = Restaurant("我的餐厅", {})
r.add_item("披萨", 10)
r.add_item("汉堡", 8)
r.print_menu() # 输出:
# 披萨: $10
# 汉堡: $8



第11章 网络编程
练习11.1:

import socket
s = (socket.AF_INET, socket.SOCK_STREAM)
(('', 80))


练习11.2:

import requests
r = ('')
print() # 输出:Google首页的HTML代码



第12章 并发编程
练习12.1:

from threading import Thread
import time
def countdown(n):
for i in range(n, 0, -1):
(1)
print(i)
t = Thread(target=countdown, args=(5,))
()


练习12.2:

from multiprocessing import Process
import os
def worker():
print(f"子进程:进程ID:{()}")
if __name__ == '__main__':
for i in range(3):
p = Process(target=worker)
() # 启动子进程
() # 等待子进程结束



第13章 数据库编程
练习13.1:

import sqlite3
conn = ('')
c = ()
("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)")
()


练习13.2:

import sqlite3
conn = ('')
c = ()
("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 25))
()



第14章 GUI编程
练习14.1:

from tkinter import *
root = Tk()
label = Label(root, text="Hello, Tkinter!")
()
()


练习14.2:

from tkinter import *
root = Tk()
button = Button(root, text="点击我")
()
def callback():
print("按钮被点击了!")
(command=callback)
()



第15章 数据分析和机器学习
练习15.1:

import numpy as np
import pandas as pd

2024-12-05


上一篇:Python 核心编程,第二版中文版

下一篇:Python计算与编程实践多媒体方法