第5周作业 #高级编程技术


- 第9章
- 9-1 餐馆
- 9-2 三家餐馆
- 9-3 用户
- 9-4 就餐人数
- 9-5 尝试登录次数
- 9-6 冰淇淋小店
- 9-7 管理员
- 9-8 权限
- 9-9 电瓶升级
- 9-14 骰子
- 第10章
- 10-1 Python学习笔记
- 10-2 C语言学习笔记
- 10-3 访客
- 10-4 访客名单
- 10-5 关于编程的调查
- 10-6 加法运算
- 10-7 加法计算器
- 10-8 猫和狗
- 10-9 沉默的猫和狗
- 10-10 常见单词

第9章



9-1 餐馆

创建一个名为Restaurant 的类,其方法init() 设置两个属性:restaurant_name 和cuisine_type 。创建一个名为describe_restaurant()的方法和一个名为open_restaurant() 的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。根据这个类创建一个名为restaurant 的实例,分别打印其两个属性,再调用前述两个方法。

class Restaurant():
    def __init__(self, name, type_):
        self.restaurant_name = name
        self.cuisine_type = type_

    def describe_restaurant(self):
        print("Welcome to " + self.restaurant_name.title())
        print("Here is the cuisine type: " + self.cuisine_type)

    def open_restaurant(self):
        print("It's business time now.")

my_restaurant = Restaurant("Little dude", "Cantonese")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()

输出:

Welcome to Little Dude
Here is the cuisine type: Cantonese
It's business time now.



9-2 三家餐馆

根据你为完成练习9-1而编写的类创建三个实例,并对每个实例调用方法describe_restaurant() 。

class Restaurant():
    --snip--

a = Restaurant("M", "Fast Food")
b = Restaurant("KFC", "Fast Food")
c = Restaurant("House of dumplings", "Northeastern")
a.describe_restaurant()
b.describe_restaurant()
c.describe_restaurant()

输出:

Welcome to M
Here is the cuisine type: Fast Food

Welcome to Kfc
Here is the cuisine type: Fast Food

Welcome to House Of Dumplings
Here is the cuisine type: Northeastern



9-3 用户

创建一个名为User 的类,其中包含属性first_name 和last_name ,还有用户简介通常会存储的其他几个属性。在类User 中定义一个名为describe_user() 的方法,它打印用户信息摘要;再定义一个名为greet_user() 的方法,它向用户发出个性化的问候。
- 创建多个表示不同用户的实例,并对每个实例都调用上述两个方法。

class User():
    def __init__(self, f_name, l_name, account):
        self.first_name = f_name
        self.last_name = l_name
        self.account = account

    def describe_user(self):
        print("\nThis is " + self.first_name.title() + ' ' + self.last_name.title())
        print("account: " + str(self.account))

    def greet_user(self):
        print("Hello!" + self.first_name.title() + ' ' + self.last_name.title())

a = User("Mary", "ast", 10923)
b = User("Jony", "ood", 45890)
a.describe_user()
a.greet_user()
b.describe_user()
b.greet_user()

输出:

This is Mary Ast
account: 10923
Hello!Mary Ast

This is Jony Ood
account: 45890
Hello!Jony Ood



9-4 就餐人数

在为完成练习9-1而编写的程序中,添加一个名为number_served 的属性,并将其默认值设置为0。根据这个类创建一个名为restaurant 的实例;打印有多少人在这家餐馆就餐过,然后修改这个值并再次打印它。 添加一个名为set_number_served() 的方法,它让你能够设置就餐人数。调用这个方法并向它传递一个值,然后再次打印这个值。 添加一个名为increment_number_served() 的方法,它让你能够将就餐人数递增。调用这个方法并向它传递一个这样的值:你认为这家餐馆每天可能接待的就餐人数。

class Restaurant():
    def __init__(self, name, type_):
        self.restaurant_name = name
        self.cuisine_type = type_
        self.number_served = 0;

    def set_number_served(self, x):
        self.number_served = x

    def increment_number_served(self, i):
        self.number_served += i



9-5 尝试登录次数

在为完成练习9-3而编写的User 类中,添加一个名为login_attempts 的属性。编写一个名为increment_login_attempts() 的方法,它将属性login_attempts 的值加1。再编写一个名为reset_login_attempts() 的方法,它将属性login_attempts 的值重置为0。 根据User 类创建一个实例,再调用方法increment_login_attempts() 多次。打印属性login_attempts 的值,确认它被正确地递增;然后,调用方 法reset_login_attempts() ,并再次打印属性login_attempts 的值,确认它被重置为0。

class User():
    def __init__(self, f_name, l_name, account):
        self.first_name = f_name
        self.last_name = l_name
        self.account = account
        self.login_attempts  = 0

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

a = User("Mary", "ast", 10923)
print(a.login_attempts)
a.increment_login_attempts()
print(a.login_attempts)
a.increment_login_attempts()
print(a.login_attempts)
a.reset_login_attempts()
print(a.login_attempts)

输出:

0
1
2
0



9-6 冰淇淋小店

冰淇淋小店是一种特殊的餐馆。编写一个名为IceCreamStand 的类,让它继承你为完成练习9-1或练习9-4而编写的Restaurant 类。这两个版本的Restaurant 类都可以,挑选你更喜欢的那个即可。添加一个名为flavors 的属性,用于存储一个由各种口味的冰淇淋组成的列表。编写一个显示这些冰淇淋的方法。创建一个IceCreamStand 实例,并调用这个方法。

class Restaurant():
    def __init__(self, name):
        self.restaurant_name = name
        self.number_served = 0

    def set_number_served(self, x):
        self.number_served = x

    def increment_number_served(self, i):
        self.number_served += i


class IceCreamStand(Restaurant):
    def __init__(self,name):
        super().__init__(name)
        self.flavors = ["Blue Moon", "Pistachio", "Chocolate", ]

    def describe_flavors(self):
        print("Here are some flavors:")
        for flavor in self.flavors:
            print("\t" + flavor)

my_shop = IceCreamStand("Z's")
my_shop.describe_flavors()

输出:

Here are some flavors:
    Blue Moon
    Pistachio
    Chocolate



9-7 管理员

管理员是一种特殊的用户。编写一个名为Admin 的类,让它继承你为完成练习9-3或练习9-5而编写的User 类。添加一个名为privileges 的属性,用于存储一个由字符串(如”can add post” 、”can delete post” 、”can ban user” 等)组成的列表。编写一个名为show_privileges() 的方法,它显示管理员的权限。创建一个Admin 实例,并调用这个方法。

class User():
    def __init__(self, f_name, l_name, account):
        self.first_name = f_name
        self.last_name = l_name
        self.account = account
        self.login_attempts  = 0

    def describe_user(self):
        print("\nThis is " + self.first_name.title() + ' ' + self.last_name.title())
        print("account: " + str(self.account))

    def greet_user(self):
        print("Hello!" + self.first_name.title() + ' ' + self.last_name.title())

    def increment_login_attempts(self):
        self.login_attempts += 1

    def reset_login_attempts(self):
        self.login_attempts = 0

class Admin(User):
    def __init__(self, f_name, l_name, account):
        super().__init__(f_name, l_name, account)
        self.privileges = ["can add post", "can delete post", "can ban user"]

    def describe_privileges(self):
        print("Here are Admin's privileges")
        for privilege in self.privileges:
            print("\t" + privilege)

admin = Admin("Peter", "King", 11111)
admin.describe_privileges()

输出:

Here is Admin's privileges
    can add post
    can delete post
    can ban user



9-8 权限

编写一个名为Privileges 的类,它只有一个属性——privileges ,其中存储了练习9-7 所说的字符串列表。将方法show_privileges() 移到这 个类中。在Admin 类中,将一个Privileges 实例用作其属性。创建一个Admin 实例,并使用方法show_privileges() 来显示其权限。

class User():
    -- snip --

class Privilege():
    def __init__(self):
        self.privileges = ["can add post", "can delete post", "can ban user"]
    def show_privileges(self):
        print("Here are privileges")
        for privilege in self.privileges:
            print("\t" + privilege)

class Admin(User):
    def __init__(self, f_name, l_name, account):
        super().__init__(f_name, l_name, account)
        self.privileges = Privilege()

admin = Admin("Peter", "King", 11111)
admin.privileges.show_privileges()

输出:

Here are privileges
    can add post
    can delete post
    can ban user



9-9 电瓶升级

在本节最后一个electric_car.py版本中,给Battery 类添加一个名为upgrade_battery() 的方法。这个方法检查电瓶容量,如果它不是85,就将它设置为85。创建一辆电瓶容量为默认值的电动汽车,调用方法get_range() ,然后对电瓶进行升级,并再次调用get_range() 。你会看到这辆汽车的续航里程增加了。

class Car():
    -- snip --

class Battery():
    -- snip --

    def upgrade_battery(self):
        if self.battery_size < 85
            self.battery_size =85

class ElectricCar(Car):
    -- snip --



9-14 骰子

模块random 包含以各种方式生成随机数的函数,其中的randint() 返回一个位于指定范围内的整数,例如,下面的代码返回一个1~6内的整数:

from random import randint
x = randint(1, 6)

请创建一个Die 类,它包含一个名为sides 的属性,该属性的默认值为6。编写一个名为roll_die() 的方法,它打印位于1和骰子面数之间的随机数。创建一个6面的骰子,再掷10次。 创建一个10面的骰子和一个20面的骰子,并将它们都掷10次。

from random import randint

class Die:
    def __init__(self, sides):
        self.sides = sides

    def roll_die(self, times):
        x = [randint(1, self.sides) for value in range(1, times)]
        print(x)


die1 = Die(6)
die1.roll_die(10)
die2 = Die(10)
die2.roll_die(10)
die3 = Die(20)
die3.roll_die(10)

输出:

[2, 5, 1, 1, 4, 4, 2, 1, 6]
[6, 8, 8, 7, 8, 7, 5, 10, 8]
[12, 18, 8, 17, 11, 8, 20, 17, 8]
[Finished in 0.3s]


第10章



10-1 Python学习笔记

在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。

filename = 'learning_python.txt'

print("Method 1:")
with open(filename) as file_object:
    contents = file_object.read()
    print(contents)

print("\nMethod 2:")
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())

print("\nMethod 3:")
with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())

输出:

Method 1:
In python you can use table, dict, set, ...
In python you can use any varible without declaring its type.
In python you can create a wonderful program.

Method 2:
In python you can use table, dict, set, ...
In python you can use any varible without declaring its type.
In python you can create a wonderful program.

Method 3:
In python you can use table, dict, set, ...
In python you can use any varible without declaring its type.
In python you can create a wonderful program.
[Finished in 0.1s]



10-2 C语言学习笔记

可使用方法replace() 将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的’dog’ 替换为’cat’ :

>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'

读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。

filename = 'learning_python.txt'
with open(filename) as file_object:
    contents = file_object.read()

print(contents.replace('python', 'C++'))

输出:

In C++ you can use table, dict, set, ...
In C++ you can use any varible without declaring its type.
In C++ you can create a wonderful program.
[Finished in 0.1s]



10-3 访客

编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。

filename = 'guest.txt'
with open(filename, 'w') as file_object:
    name = input("Please input your name:")
    file_object.write(name + '\n')



10-4 访客名单

编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

filename = 'guest_book.txt'
while True:
    with open(filename, 'a') as file_object:
        name = input("Please input your name:")
        print("Hello, " + name.title())
        file_object.write(name.title() + ' has accessed program.\n')

输出:

Please input your name:lily
Hello, Lily
Please input your name:mary
Hello, Mary
Please input your name:......

文件输出:

Lily has accessed program.
Mart has accessed program.



10-5 关于编程的调查

编写一个while 循环,询问用户为何喜欢编程。每当用户输入一个原因后,都将其添加到一个存储所有原因的文件中。

filename = 'guest_research.txt'
with open(filename, 'w') as file_object:
    while True:
        reason = input("So why do you like programing?")
        file_object.write(reason + '\n')



10-6 加法运算

提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。

def addtion(first_nuber, second_number):
    try:
        first_nuber = int(first_nuber)
        second_number = int(second_number)
    except ValueError:
        print("Illegal number to add!")
    else:
        sum_number = first_nuber + second_number
        print(str(first_nuber) + ' + ' + str(second_number) + ' = ' + str(sum_number))

addtion(1, 2)
addtion(1, 'a')
addtion(5.5, 6.7)
addtion('b', 0)

输出:

1 + 2 = 3
Illegal number to add!
5 + 6 = 11
Illegal number to add!
[Finished in 0.1s]



10-7 加法计算器

将你为完成练习10-6而编写的代码放在一个while 循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

代码同上


10-8 猫和狗

创建两个文件cats.txt和dogs.txt,在第一个文件中至少存储三只猫的名字,在第二个文件中至少存储三条狗的名字。编写一个程序,尝试读取这些文件,并将其内容打印到屏幕上。将这些代码放在一个try-except 代码块中,以便在文件不存在时捕获FileNotFound 错误,并打印一条友好的消息。将其中一个文件移到另一个地方,并确认except 代码块中的代码将正确地执行。

def myPat(filename):
    try:
        with open(filename) as file_object:
            contents = file_object.read();
    except FileNotFoundError:
        print("File <" + filename + "> does not exist.")
    else:
        pats = contents.split()
        for pat in pats:
            print(pat)


myPat('cat.txt')
myPat('dog.txt')

输出:

File <cat.txt> does not exist.
dog1
dog2
dog3
[Finished in 0.1s]



10-9 沉默的猫和狗

修改你在练习10-8中编写的except 代码块,让程序在文件不存在时一言不发。

def myPat(filename):
    try:
        with open(filename) as file_object:
            contents = file_object.read();
    except FileNotFoundError:
        pass
    else:
        pats = contents.split()
        for pat in pats:
            print(pat)


myPat('cat.txt')
myPat('dog.txt')

输出:

dog1
dog2
dog3
[Finished in 0.1s]



10-10 常见单词

访问项目Gutenberg(http://gutenberg.org/ ),并找一些你想分析的图书。下载这些作品的文本文件或将浏览器中的原始文本复制到文本文件中。你可以使用方法count() 来确定特定的单词或短语在字符串中出现了多少次。例如,下面的代码计算’row’ 在一个字符串中出现了多少次:

>>> line = "Row, row, row your boat"
>>> line.count('row')
2
>>> line.lower().count('row')
3

请注意,通过使用lower() 将字符串转换为小写,可捕捉要查找的单词出现的所有次数,而不管其大小写格式如何。 编写一个程序,它读取你在项目Gutenberg中获取的文件,并计算单词’the’ 在每个文件中分别出现了多少次。

with open("THE_THREE_MUSKETEERS.txt") as file_object:
    contents = file_object.read();

words = ['liberty', 'freedom', 'love', 'the', 'war', 'beautiful', 'wine', 'kill']
for word in words:
    print(word, end = ': ')
    print(contents.lower().count(word))

输出:

liberty: 28
freedom: 2
love: 320
the: 18363
war: 561
beautiful: 87
wine: 97
kill: 140
[Finished in 0.1s]

猜你喜欢

转载自blog.csdn.net/yyyyzxc1234/article/details/79846566
今日推荐