python入门学习

       最近开始学习python语言,看了一些视频,选择了《python编程:从入门到实践》这本书。看书跟着学,书前文推荐是每天看一章,但实际做下来,没课的时候一天可以看四章,上课的时候基本一上上半天,所以一天看两章问题不大。

      本来打算配合小甲鱼的python视频一起学习,但由于实在没时间所以放弃了。现在学到书的第七章,感觉还不错。

      分享一些我的学习笔记和这本书的一些课后习题答案给大家。为自己的学习生活也做一个简单的记录。

        总的说来,这本书是本非常好的书,对于有C语言基础的人来说学习起来上手会很快很轻松。

目录

常用命令

报错汇总

Python 学习中遇到的问题,欢迎大家一起分享答案:

第二章学习笔记

第三章学习笔记

第四章  操作列表-学习笔记

练习答案

第五章 if语句

练习

第六章 字典

    第七章 用户输入和while循环

练习

第八章 函数

练习


常用命令

  1. Spyder清屏
  • 清除变量

        在IPython中输入reset命令,得到提示输入y确认即可

  • 清空IPthon中的输入历史记录

        在控制台输入clear即可

        使用快捷键Ctrl + L

报错汇总

1.EOL while scanning string literal

        Print少打了一个双引号/打成了中文双引号

2.invalid character in identifier

        意思是:标志符中的无效字符

                if后面的冒号打成了中文输入法下的冒号

3.invalid syntax

        语法错误

               字典中键值对之间忘记加逗号了

               字典嵌套字典时,被嵌套的字典大括号前应为:写成了=。

               字典嵌套字典时,被嵌套的字典和字典大括号之间也要有,。

               访问字典中某一键值时[]后面加了.。

               在函数这一章,如果形参/实参是字符串的话,形参不需要加双引号,实参需要

4.f-string expression part cannot include a backslash

       意思是f字符串中不能出现反斜杠

5.'function' object is not subscriptable

        “函数”对象不可下标

               出现原因:一是调用自定义函数时要用圆括号()而不是方括号[ ]。

                                二是自定义函数名不 能与已有变量重名

6.unindent does not match any outer indentation level

        未缩进与任何外部缩进级别不匹配

                a.删除缩进时没有删除干净

7.TypeError: object() takes no parameters

        TypeError:对象()不接受任何参数

                a.init方法前后各有两个!两个下划线,一共有四个下划线!

8. name 'describe_restaurant' is not defined

        这个错误常见于语法出现错误

                a.定义类后调用这个方法出现了提示错误。是因为方法前忘记加入实例.了

9.__init__() missing 1 required positional argument: 'privileges'

        __init_u3;()缺少1个必需的位置参数:“privileges”

                子类忘记运行super函数了

10.ValueError:I/O operation on closed file.

     或者出现的还有:NameError: name 'open_object' is not defined

        这是python读写文件经常会遇到的错误。错误原因在于:

        with语句后面忘记加as语句了。


Python 学习中遇到的问题,欢迎大家一起分享答案:

1.打印的时候如何只打印列表的名称,而不是打印列表的内容

第二章学习笔记

1. print(name.title());此时不需要引号

2. print(f"hello,{name.title()}"):注意此时需要引号,并且函数内的东西要用大括号括起来

练习答案

##2-5
name='albert einsetin'
message='a person who never made a mistake never tried anythiing new'
print(name.title())
print(f"{name.title()} once said {message}")
##2-9
fav_num=8
msg="my favorite number is "+str(fav_num)+"."
print(msg)

第三章学习笔记

1.注意if和while后都有一个冒号:

2.true+true=2

3.转换为整型,python会截断处理,不会四舍五入。

4.获得类型的信息一般有两种函数:type 和 isinstance

5. Python 中 / 与 // 的区别

        在Python中“/”表示浮点数除法,返回浮点结果,也就是结果为浮点数,而“//”在Python中表示整数除法,返回不大于结果的一个最大的整数,意思就是除法结果向下取整。

6.sorted的参数可以没有,也可以有两个。

         例如打印与字母顺序相反的顺序时:print(sorted(travels,reverse=True))

7.但如果是sort的话,只有一个参数

         travels.sort(reverse=True)

        print(travels)

        且注意sorted不能采用这种方法

练习答案

#3-8放眼世界
travels=['newyork','thailand','japan','london','singpore']
print(travels)
print(sorted(travels))
print(travels)
print("按照相反字母顺序打印")
print(sorted(travels,reverse=True))

print("核实一下是否是原来的顺序")
print(travels)
print("反转顺序")
travels.reverse()
print(travels)
print("再次反转")
travels.reverse()
print(travels)
print("使用sort")
travels.sort()
print(travels)
print("sort反顺序")
travels.sort(reverse=True)
print(travels)

第四章  操作列表-学习笔记

1.for语句后一定要记得带冒号,不然会报错!

练习答案

#4-1披萨

pizzas=['pianapple','peigen','potato']

for pizza in pizzas:

    print("i like "+pizza+' pizza')

print("i really love pizza")



#4-2

con_animals=['rabbit','cat','dog']

for animal in con_animals:

    print('A '+animal+' would make a great pet')

print('Any of these animals would make a great pet')

#4-3数到20

numbers=[num for num in range(1,21)]

print(numbers)



4-4数到一百万

numbers=[]

for num in range(101):

    numbers.append(num)

print(numbers)

print(min(numbers))



#4-7奇数

numbers=[]

for num in range(1,21,2):

    numbers.append(num)

    print(num)



#4-9立方解析

numbers=[]

for num in range(1,11):

    numbers.append(num**3)

print(numbers)



print("采用立体解析的方法如下")

numbers=[num**3 for num in range(1,11)]

print(numbers)



#4-10切片

con_animals=['rabbit','cat','dog','panda','bird','lion']

print(con_animals[0:3])

print(con_animals[1:5])

print(con_animals[3:])



#4-11你的披萨我的披萨

pizzas=['pianapple','peigen','potato']

friends_pizza=pizzas[:]

pizzas.append('tomato')

friends_pizza.append('banana')

print("My favorite pizzas are:")

for pizza in pizzas[:]:

    print(pizza)

for pizza in friends_pizza[:]:

    print(pizza)

#4-13自助餐

foods=('potato','hundu','vegetables','pizza','humberger')

for food in foods:

    print(food)

foods=('potato','hulatang','buttonsope','pizza','humberger')

for food in foods:

    print(food)

第五章 if语句

练习

#5-1

car='subaru'

print("Is car == 'subaru'?I predict True")

print(car=='subaru')



#5-5外星人颜色3

alien_color='red'

if alien_color == 'green':

    print("你得到了五分")

elif alien_color=='yellow':

    print("你得到了十分")

else:

    print("你得到了十五分")



#5-6人生的不同阶段

age=1

if age<2:

    print("这个人是个婴儿")

elif age>2 and age<4:

    print("这个人是个幼儿")

elif age>4 and age<13:

    print("这个人是个儿童")

elif age>13 and age<20:

    print("这个人是个青少年")

elif age>20 and age<65:

    print("这个人是个成年人")

elif age>65:

    print("这个人是个老年人")

   

#5-7喜欢的水果

favorite_fruits=['pineapple','dragon','mihoutao']

if 'pineapple' in favorite_fruits:

    print("you really like pineapple")



#5-8-9以特殊方式跟管理员打招呼

name_list=['admin','acky','boubou','chick','kevin']

name=input()

if name:

    if name == 'admin':

        print("hello admin,would you like to see a status report?")

    else:

        print("hello jaden,thank you for logging in again")

else:

     print("we need to find some users")

   



#5-10检查用户名

current_users=['admin','acky','boubou','chick','kevin']

new_users=['acky','nelson','kaka','momoco','kenken']

#print("请输入您的用户名:")

#name=input()

for name in new_users:

    if name in current_users:

        print("用户名已被使用")

    else:

        print("用户名未被使用")



#5-11序数

numbers=[1,2,3,4,5,6,7,8,9,10]

for number in numbers:

    if number == 1:

        print(f"{number}st")

    elif number == 2:

        print(f"{number}nd")

    else:

        print(f"{number}th")

第六章 字典

练习

#6-1人

person={'名':'kk',

        '姓':'朴',

        '年龄':'22',

        '居住城市':'上海',

        }

print(f"我姓{person['姓']}")



#6-7人们

person_kk={'名':'kk',

        '姓':'朴',

        '年龄':'22',

        '居住城市':'上海',

          }

person_cc={'名':'cc',

        '姓':'杨',

        '年龄':'32',

        '居住城市':'北京',

          }

person_aa={'名':'aa',

        '姓':'r',

        '年龄':'27',

        '居住城市':'巴黎',

          }

people=[person_kk,person_cc,person_aa]

for person in people:

    print(person)



#6-8宠物

pet_dog={

         'name':'dog',

         'owner':'cc',

        }

pet_cat={

         'name':'cat',

         'owner':'kk',

        }

pet_fish={

         'name':'fish',

         'owner':'aa',

        }

pets=[pet_dog,pet_cat,pet_fish]

for pet in pets:

    print(pet)



#6-9喜欢的地方(字典中嵌套列表)

favorite_places={

                  'kk':['london','tokyo','korea'],

                  'aa':['paris','nepol','africa'],

                  'cc':['shangahai','kaifeng','hangzhou'],

                }

for name,places in favorite_places.items():

    print(f"{name.title()}'s favorite places are:")

    for place in places:

        print(place.title())



#6-11 城市(字典嵌套字典)

cities={

        'shanghai':{

                    'country':'china',

                    'population':'1kw',

                    'fact':'beauty',

                    },

        'tokyo':{

                'country':'japan',

                'population':'50w',

                'fact':'far',

                },

        'london':{

                 'country':'england',

                 'population':'100w',

                 'fact':'wet',

                 },

       

        }

for city_name,city_info in cities.items():

    print(f"city's name is {city_name.title()}")

    print(f"他属于{city_info['country']}")

    print(f"它拥有人口{city_info['population']}")

    print(f"它最大的特点是{city_info['fact']}")

    第七章 用户输入和while循环

练习

#7-1汽车租赁

car=input("let me see if i can find you subaru? ")

print(car)



#7-2餐馆定位

number=input('有多少人来吃饭? ')

number=int(number)

if number >8:

    print("没有空桌")

else:

    print("有空座")

#7-4披萨配料

prompt="\n please input a series of pizzas adding"

prompt += '\n(Enter the quit when you finished)'

while True:

    adding=input(prompt)

    if adding == 'quit':

        break

    else:

        print(f"我们将在披萨中加入配料{adding}")



#7-5电影票

prompt='请输入你的年龄'

while True:

    age=input(prompt)

    age=int(age)

    if age < 3:

        print('你免费')

        break

    elif age >3 and  age < 12:

        print('你需要支付十美元')

        break

    elif age > 12:

        print('你需要支付十五美元')

        break



#7-8 熟食店

sandwich_orders=['tunnayu','niuyouguo','peigen']

finished_sandwiches=[]

while sandwich_orders:

    finished_sandwich=sandwich_orders.pop()

    print(f'i made your {finished_sandwich} sandwich')

   

    finished_sandwiches.append(finished_sandwich)

print("接下来是做好的列表")

for finished_sandwich in finished_sandwiches:

    print(finished_sandwich.title())

   

   

#7-9 五香烟熏牛肉卖完了

sandwich_orders=['tunnayu','pastrami','niuyouguo','pastrami','peigen','pastrami']

finished_sandwiches=[]

while 'pastrami' in sandwich_orders:

    sandwich_orders.remove('pastrami')

print(sandwich_orders)

第八章 函数

练习

#8-1消息
def display_message():
        """指出你在本章学的是什么的信息"""
        print("我在本章学的是函数")
display_message()

#8-2喜欢的图书
def favorite_book(title):
    print(f"One of my favorite books is {title}")
favorite_book("Alice in Wonderland")

#8-3T恤
def make_shirt(size,word):
    print(f"这个T恤的尺寸是{size},印在上面的字样是{word}")
print("这种调用方法是位置实参调用:")
make_shirt('m','makabaka')

print("下面这种是关键字实参调用:")
make_shirt(word='yigubigu',size='xs')
    

#8-4大号T恤
"""使用默认值"""
def make_shirt(size,word='i love python'):
    print(f"这个T恤的尺寸是{size},印在上面的字样是{word}")

make_shirt('L')
make_shirt('M')
make_shirt('s','i love c')

#8-5 城市
def describe_city(city_name,city_country='china'):
    print(f"{city_name} in {city_country}")
describe_city('shanghai')
describe_city('kaifeng')
describe_city('london','england')

#8-6城市名
def city_country(city_name,city_country):
    """打印城市的名字和所属国家"""
    print(city_name,city_country)
name_of_city=input("请输入城市名字:")
name_of_country=input("请输入国家的名字:")
city_country(name_of_city,name_of_country)

#8-7专辑
def make_album(singer,name,number=None):
    music={
            'singer':singer,
            'name':name,
            }
    if number:
        music={
                'singer':singer,
                'name':name,
                'number':number,
              }
    return music
music_1=make_album('xusong','yasugongshang')
music_2=make_album('yizhiliulian','haidi')
music_3=make_album('dazhangwei','huluwa','3')
print(music_1)
print(music_2)
print(music_3)

#8-8用户的专辑
def make_album(singer,name,number=None):
    music={
            'singer':singer,
            'name':name,
            }
    if number:
        music={
                'singer':singer,
                'name':name,
                'number':number,
              }
    return music
while True:
    print("\n 接下来请输入你喜欢的歌手相关信息。\n输入q可以退出")
    name_of_music=input('请输入你喜欢的专辑名字:')
    if name_of_music =='q':
        break
    name_of_singer=input('请输入你喜欢的歌手名字:')
    if name_of_singer=='q':
        break
    print(name_of_music,name_of_singer)

#8-9消息
def show_messages(messages):
    """打印列表中的每条文本消息"""
    for message in messages:
        print(message)
msgs=['yigubigu','makabala','tombulibo','xiaodiandian']
show_messages(msgs)


#8-10发送消息
def send_messages(need_to_send,have_sent):
    """
    将需要发送的信息打印出来,
    并且将打印出来的消息移送到新列表:已打印的列表中去
    """
    while need_to_send:
        now_sent=need_to_send.pop()
        print(f"现在正在打印的是{now_sent}")
        have_sent.append(now_sent)
        
def print_messages(messages):
    """
    打印消息列表
    """
    print(f"接下来打印的是{messages}列表:")
    for message in messages:
        print(message)
        
msgs=['yigubigu','makabala','tombulibo','xiaodiandian']
h_msg=[]
send_messages(msgs,h_msg)

print_messages(msgs)
print_messages(h_msg)

#8-11消息归档
def send_messages(need_to_send,have_sent):
    """
    将需要发送的信息打印出来,
    并且将打印出来的消息移送到新列表:已打印的列表中去
    传递消息列表的副本
    """
    need_to_send_copy=need_to_send[:]
    while need_to_send_copy:
        now_sent=need_to_send_copy.pop()
        print(f"现在正在打印的是{now_sent}")
        have_sent.append(now_sent)
        
def print_messages(messages):
    """
    打印消息列表
    """
    print(f"接下来打印的是{messages}列表:")
    for message in messages:
        print(message)
        
msgs=['yigubigu','makabala','tombulibo','xiaodiandian']
h_msg=[]
send_messages(msgs,h_msg)

print_messages(msgs)
print_messages(h_msg)

#8-12三明治
def sandwich(sum,*toppings):
    """
        属于8.5.1,一个*的结合使用位置实参和任意数量实参问题
        先输入要加的配料种数,再使用任意数量实参来输入具体要加的种类
    """
    print(f"你一共要加{sum}种配料?")
    print("具体配料如下:")
    for topping in toppings:
        print(f"{topping}")
sandwich(16,'a','b','c')

#8-13用户简介
def build_profile(first,last,**user_info):
    """
       创建一下字典,其中包含我们所知道的用户的一切
       任意数量实参是*,
       任意数量关键字实参是**
    """
    user_info['first_name']=first
    user_info['last_name']=last
    return user_info
user_profile = build_profile(
                              'piao','kk',
                              location='shanghai',
                              field='automation',
                              hobby='dance',
                             )
print(user_profile)

#8-14汽车
def build_car(manu,size,**car_info):
    
    """
        将汽车信息存储在字典中
    """
    car_info['manu']=manu
    car_info['size']=size
    return car_info
car=build_car(
                'subaru',
                'outback',
                color='blue',
                two_package='True',
             )
print(car)

第九章 类

学习笔记

1.关于self的理解

        self其实是类中的实例,例如下面9-1的练习,self就相当于my_rest,当创建实例时,你创建的实例将自动传至self中,他是一个指向实例本身的引用,让实例可以访问类中的属性和方法。

        所以下例my_rest.open_resturant()=Restaurant.open_restaurant(my_rest).

练习

#9-1餐馆
class Restaurant:
    """一次描述餐馆的简要尝试"""
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type

    def describe_restaurant(self):
        print(self.restaurant_name)
        print(self.cuisine_type)
        
    def open_restaurant(self):
        print("餐馆正在营业。")
        
my_rest=Restaurant('kk','paper')
my_rest.describe_restaurant()
my_rest.open_restaurant()

#9-3用户
class User:
    """包含用户信息的一个类"""
    def __init__(self,f_name,l_name):
        self.f_name=f_name
        self.l_name=l_name
        
    def describe_user(self):
        print(f'first is {self.f_name}')
        print(f'last4 is {self.l_name}')
        
    def greet_user(self):
        print(f'hello {self.f_name}{self.l_name}')
        
my=User('piao','kk')
my.describe_user()
my.greet_user()

#9-4就餐人数
class Restaurant:
    """一次描述餐馆的简要尝试"""
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
        self.number_served=25
 
    def describe_restaurant(self):
        print(self.restaurant_name)
        print(self.cuisine_type)
        
    def open_restaurant(self):
        print("餐馆正在营业。")
        print(f"这个店已经接待了{self.number_served}位客人")
    def  set_number_served(self,people):
        """
        这个方法是为了设置就餐人数
        """
     
        self.number_served=people  
        print(f"就餐的人数{self.number_served}")
    def increment_number_served(self,dizeng):
        """将就餐人数递增某个特定值"""
        self.number_served+=dizeng
        print(f"递增后的就餐人数是{self.number_served}")
        
my_rest=Restaurant('kk','paper')
my_rest.describe_restaurant()
my_rest.set_number_served(56)
my_rest.increment_number_served(10)
my_rest.open_restaurant()

#9-5尝试登陆次数
class User:
    """包含用户信息的一个类"""
    def __init__(self,f_name,l_name):
        self.f_name=f_name
        self.l_name=l_name
        self.login_attempts=9
        
    def describe_user(self):
        print(f'first is {self.f_name}')
        print(f'last4 is {self.l_name}')
        
    def greet_user(self):
        print(f'hello {self.f_name}{self.l_name}')
        print(f"你已经登陆{self.login_attempts}次啦")
        
    def increment_login_attempts(self,walk):
        self.login_attempts+=walk
        
    def reset_login_attempts(self):
        self.login_attempts=0
        print(f"你已经重置啦,现在的登陆次数是{self.login_attempts}")
        
my=User('piao','kk')
my.describe_user()
my.increment_login_attempts(1)
my.greet_user()
my.reset_login_attempts()

#9-6冰淇淋小店
class Restaurant:
    """一次描述餐馆的简要尝试"""
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type
        self.number_served=25
 
    def describe_restaurant(self):
        print(self.restaurant_name)
        print(self.cuisine_type)
        
    def open_restaurant(self):
        print("餐馆正在营业。")
        print(f"这个店已经接待了{self.number_served}位客人")
    def  set_number_served(self,people):
        """
        这个方法是为了设置就餐人数
        """
     
        self.number_served=people  
        print(f"就餐的人数{self.number_served}")
    def increment_number_served(self,dizeng):
        """将就餐人数递增某个特定值"""
        self.number_served+=dizeng
        print(f"递增后的就餐人数是{self.number_served}")
        
class IceCreamStand(Restaurant):
    def __init__(self,restaurant_name,cuisine_type):
        super().__init__(restaurant_name,cuisine_type)
        self.flavors=['sweet','salt','ku','suan']
    def ice_flavors(self):
        print(self.flavors)
        
ice=IceCreamStand('kk','paper')
ice.ice_flavors()

#9-7管理员
class User:
    """包含用户信息的一个类"""
    def __init__(self,f_name,l_name):
        self.f_name=f_name
        self.l_name=l_name
        self.login_attempts=9
        
    def describe_user(self):
        print(f'first is {self.f_name}')
        print(f'last4 is {self.l_name}')
        
    def greet_user(self):
        print(f'hello {self.f_name}{self.l_name}')
        print(f"你已经登陆{self.login_attempts}次啦")
        
    def increment_login_attempts(self,walk):
        self.login_attempts+=walk
        
    def reset_login_attempts(self):
        self.login_attempts=0
        print(f"你已经重置啦,现在的登陆次数是{self.login_attempts}")
class Admin(User):
    """继承于User这一类"""
    def __init__(self,f_name,l_name):
        """初始化父类的特性,再初始化子类特有的特性"""
        super().__init__(f_name,l_name)
        self.privileges=['can add post','can delete post','can be user']
    def show_privileges(self):
        print(f"管理员的权限是:{self.privileges}")

admin=Admin('piao','kk')
admin.show_privileges()


#9-8权限

class Privileges:
    """只有一个存储了字符串列表的属性"""
    def __init__(self):
        self.privileges=['can add post','can delete post','can be user']

    def show_privileges(self):
#        for privilege in self.privileges:
        print(f"管理员的权限是:{self.privileges}")
        
class Admin:
    def __init__(self,f_name,l_name):
        self.privileges=Privileges()

admin=Admin('piao','kk')
admin.privileges.show_privileges()


#9-10 导入restaurant类
class Restaurant:
    """一次描述餐馆的简要尝试"""
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name=restaurant_name
        self.cuisine_type=cuisine_type

    def describe_restaurant(self):
        print(self.restaurant_name)
        print(self.cuisine_type)
        
    def open_restaurant(self):
        print("餐馆正在营业。")
        
#my_rest=Restaurant('kk','paper')
#my_rest.describe_restaurant()
#my_rest.open_restaurant()
#Restaurant.open_restaurant(my_rest)

第十章学习笔记

#10-1python学习笔记
with open('learning_python.txt') as file_object:
    contents=file_object.read()
print('第一次打印:')
print(f'{contents}')

print('第二次打印:')
filename='learning_python.txt'
with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
        
print('第三次打印')
filename='learning_python.txt'
with open(filename) as file_object:
    lines=file_object.readlines()
    
for line in lines:
    print(line.rstrip())


#10-2 C语言学习
filename='learning_python.txt'
with open(filename) as file_object:
    lines=file_object.readlines()
    
for line in lines:
    line=line.replace('Python','C')
    print(line.rstrip())

#10-3访客
name=input('请输入你的名字:')

filename='guest.txt'
with open(filename,'w') as file_object:
    file_object.write(name)

#10-4访客名单
print('接下来请按照提示输入你的名字,输入q可自动退出')
filename='guest_book.txt'

with open(filename,'w') as file_object:
    name=' '
    while(name != 'q'):
        name=input('请输入你的名字:')
        print(f'welcome {name}!!!')
        file_object.write(f'{name}\n')
        
#10-5调查
print('这个程序是询问你为何喜欢编程?输入原因可以储存,输入q可以直接退出')

filename='reason_for_coding.txt'

with open(filename,'w') as file_object:
    reason=' '
    while reason != 'q':
        reason=input('你为什么喜欢编程?')
        file_object.write(f'{reason}\n')

第十一章 测试代码

#11-1 城市和国家
def get_city_country(city,country):
    """函数接受城市和国家的字符串"""
    full=f'{city} {country}'
    return full

测试函数:
import unittest
from city_functions import get_city_country
class CityTest(unittest.TestCase):
    """测试city_functions类"""
    
    def test_city_country(self):
        formatted_name=get_city_country('上海','中国')
        self.assertEqual(formatted_name,'上海 中国')
        
if __name__=='__main__':
    unittest.main()


#11-2人口数量
def get_city_country(city,country,population=''):
    """将人口设置为可选择项"""
    if population:
        full=f'{city} {country}——population {population}'
    else:
        full=f'{city} {country}'
    return full
import unittest
from city_functions import get_city_country
class CityTest(unittest.TestCase):
    """测试city_functions类"""
    
    def test_city_country(self):
        formatted_name=get_city_country('上海','中国','一千万')
        self.assertEqual(formatted_name,'上海 中国——population 一千万')
        
if __name__=='__main__':
    unittest.main()

#11-3 雇员
class Employee:
    """类来存储雇员的信息"""
    def __init__(self,first_name,last_name,salary):
        """存储名姓和年薪"""
        self.first_name=first_name
        self.last_name=last_name
        self.salary=salary
        
    def give_raise(self,addition=600):
        self.salary+=addition

import unittest
from employee import Employee

class TestEmployee(unittest.TestCase):
    """针对Employee类的测试"""
    def setUp(self):
        """创建名姓和年薪的实例,供使用的测试方法使用"""
        self.my_info=Employee('朴','kk',200)
        
    def test_give_default_raise(self):
        """测试给予默认加薪"""
        self.my_info.give_raise()
        self.assertEqual(self.my_info.salary,800)
    
    def test_give_custom_raise(self):
        """测试给客户加薪"""
        self.my_info.give_raise(1000)
        self.assertEqual(self.my_info.salary,1200)
        
if __name__=='__main__':
    unittest.main()

你可能感兴趣的:(python学习记录,python)