Python基础实践

#
a.title() 首字母大写 
print("yuanyuan song".title())
>> Yuanyuan Song


#
\n 回车
\t 制表符


#
for k, v in map.items() :
    print("key:" + k)
    print("value: + v)


#
for k in map.keys() : #Or  for k in map:
    print("key:" + k)


# 不在map的keys列表中
if 'erin' not in favorite_languages.keys() :
    print(" erin not in !!")


# 按照键值顺序,固定
for name in sorted(favorite_languages.keys()) :
    print(name.title())


# 打印values
for value in favorite_languages.values() :
    print(value.title())


# 打印values不重复
for value in set(favorite_languages.values()) :
    print(value.title())


# map的key在list中
friends = ['jen', 'edward'] # 列表
for name in favorite_languages.keys() :
    print(name.title())
    if name in friends : # 在列表中
        print(" Hi" + name.title() + 
            ", I see your favorite language is " + 
            favorite_languages[name].title() + "!")


# 打印list
a_0 = {'color' : 'green', 'points' : 5}
a_1 = {'color' : 'yellow', 'points' : 10}
a_2 = {'color' : 'red', 'points' : 15}
a_list = [a_0, a_1, a_2]
for a in a_list :
    print(a)


# 动态增list元素 & 打印list的前多少个 & 求list的长度
b_list = []
for i in range(30) :
    new_b = {'color' : 'green', 'points' : 5, 'speed' : 'slow'}
    b_list.append(new_b)


for b in b_list[:5] :
    print(b)
print("...")
print("Total number of b:" + str(len(b_list)))


# list 条件判断
for b in b_list[0:3] : # 0开始的3个元素
    if b['color'] == 'green' :
        b['color'] = 'yellow'
        b['speed'] = 'fast'
        b['points'] = 10
    elif b['color'] == 'yellow' :
        b['color'] = 'red'
        b['speed'] = 'fast'
        b['points'] = 15


for b in b_list[:5] :
    print(b)
print("...")


# map里嵌套list
favorite_language = {
    'hailong' : ['C', 'C++', 'Python'],
    'jack' : ['C'],
    'meimei' : ['Java', 'Go'],
    'yuanyuan' : ['H5'],
    }


for k, v in favorite_language.items() :
    if len(v) == 1 :
        print("\n" + k.title() + " has one favorite:")
    else :
        print("\n" + k.title() + " has some favorite language:")
    for l in v :
        print("\t" + l.title())


# map里嵌套map
users = {
    'aeinstein' : {
        'first' : 'albert',
        'last' : 'aeinstein',
        'location' : 'new york'
        },
    'mcurie' : {
        'first' : 'marie',
        'last' : 'curie',
        'location' : 'pairs'
        }
    }


for name, info in users.items() :
    print("\n username:" + name.title())
    full_name = info['first'] + " " + info['last']
    location = info['location']


    print("\t full name is:" + full_name.title())
    print("\t location:" + location.title())


# 接收输入,与用户交互
message = input("tell me some message:")
print (message)
    # 如果用的是python2.7  请用raw_input


# 拼接多行字符串
prompt = "balabalabala"
prompt += "\nwhat is your name:"
message = input(prompt)
print("\nHello, " + message + "!")


# while使用
start = 1
while start <= 5 :
    print("\n number:" + str(start))
    start += 1


# while & bool
prompt = "input value, and i will echo to you,"
prompt += "\n if you enter 'quit', exit programe:"
message = ""
active = True
while active :
    message = input(prompt)


    if message == 'quit' :
        active = False
    else :
        print(message)


# break的使用
prompt = "\n tell me what city do you go:"
message = ""
while True :
    message = input(prompt)


    if message == 'quit' :
        break


    print("the city you want to go is:" + message.title())


# continue的使用
cur_number = 0
while cur_number < 10 :
    cur_number += 1


    if cur_number % 2 == 0 :
        continue


    print(cur_number)


# 遍历list & list放在while中删除 & list的pop
unconfirm_list = ['a', 'b', 'c']
confirm_list = []
while unconfirm_list : # 只能用while 不能用 for
    cur = unconfirm_list.pop() # c -> b ->a


    print("cur user is:" + cur.title())
    confirm_list.append(cur) # 加入


for cu in confirm_list :
    print("confirm member:" + cu.title())


# list的循环遍历删除(删除多个元素)
pet_list = ['a', 'b', 'c', 'a', 'a', 'd', 'f']
print(pet_list)
while 'a' in pet_list :
    pet_list.remove('a')


print(pet_list)


# while & input & map
response = {}
b_active = True
while b_active :
    name = input("What's you name:")
    mountain = input("What moutain do you like:")


    response[name] = mountain


    ack = input("do you want continue(yes/no):")
    if ack == 'no' :
        b_active = False
    
for k, v in response.items() :
    print("Hi, " + k + ", do you want climb " + v)


# 函数
def sayHello() :
    """ say hello """  #[docstring] 生成文档用的注释
    print("Hello!!!!")


sayHello()


# 函数 带参数
def sayHello(name) :
    """ say hello """ # docstring
    print("Hello " + name.title() + " !")


sayHello('hailong')


# 函数 位置实参 多个
def showAnimal(type, name) :
    print("\n I have a type:" + type.title() + " animal, name:" + name.title())


showAnimal('cat', 'mimi')
showAnimal('dog', 'taotao')


# 函数 关键字实参 再也不用担心传的顺序不对了
def showAnimal(type, name) :
    print("\n I have a type:" + type.title() + " animal, name:" + name.title())


showAnimal(type='cat', name='mimi')
showAnimal(name='mimi', type='cat')


# 函数 参数 默认值
def showAnimal(name, type='dog') :
    print("\n I have a type:" + type.title() + " animal, name:" + name.title())


showAnimal(name='mimi')
showAnimal('taotao')


# 函数 返回值
def get_clean_name(first, family) :
    full_name = first + ' ' + family
    return full_name.title()


my_name = get_clean_name('jack', 'shi')
print(my_name)


# 函数 默认值 判断字符串是否为空
def get_formatted_name(first, last, middle='') :


    if middle : # 直接判断是否为空
        full_name = first + ' ' + middle + ' ' + last
    else :
        full_name = first + ' ' + last


    return full_name.title()


my_name = get_formatted_name('jack', 'shi')
print(my_name)
my_name = get_formatted_name('jack', 'shi', 'tang')
print(my_name)


# 函数 返回map
def build_person(first, last) :
    person = {'first' : first, 'last' : last}
    return person


my_person = build_person('hailong', 'shi')
print(my_person)


# 函数 返回map 默认值
def build_person(first, last, age='') :
    person = {'first' : first, 'last' : last}
    if age :
        person['age'] = age
    return person


my_person = build_person('hailong', 'shi', 27) # map的age为int型27 以实参为准
print(my_person)


# 函数 返回值 & while & break
def get_formatted_name(first, last) :
    full_name = first + ' ' + last
    return full_name.title()


while True :
    f_name = input("Input first name:")
    if f_name == 'q' :
        break
    l_name = input("Input last name:")
    if l_name == 'q' :
        break


    my_fullname = get_formatted_name(f_name, l_name)
    print(my_fullname)


# 函数 传参list & 字符串拼接
def greet_user(names) :
    for name in names :
        msg = "Hello " + name.title() + "!"
        print(msg)


user_list = ['hailong', 'yuanyuan', 'taotao']
greet_user(user_list)


# 函数 参数list回传 & docstring &
def printModules(un, ed) :
    """
    docstring 说明 # 可以嵌套注释
    """
    while un :
        cur = un.pop()
        print("pop from list:" + cur)
        ed.append(cur)


def showModule(l) :
    for node in l :
        print(node)
    
my_list = ['a', 'b', 'c', 'd']
ed_list = []
printModules(my_list, ed_list) #回传 ed_list
showModule(ed_list)


# 函数 参数list不能被函数修改
def printModules(un, ed) :
    """
    docstring 说明 # 说明
    """
    while un :
        cur = un.pop()
        print("pop from list:" + cur)
        ed.append(cur)


def showModule(l) :
    for node in l :
        print(node)
    
my_list = ['a', 'b', 'c', 'd']
ed_list = []
printModules(my_list[:], ed_list) # 传my_list的切片副本 不会被函数内部修改
showModule(my_list)
showModule(ed_list)


# 函数 可变实参
def make_pizza(*toppings) : # 注意toppings前面的*
    print("Make a pizz need some toppings:")
    for t in toppings :
        print("- " + t)


make_pizza('a')
make_pizza('a', 'b', 'c', 'd')


# 位置实参 & 可变实参(可变实参用list收藏)
def make_pizza(size, *toppings) :
    print("Make a " + str(size) + " inch pizz need some toppings:")
    for t in toppings :
        print("- " + t)


make_pizza(11, 'a')
make_pizza(18, 'a', 'b', 'c', 'd')


# 位置实参 & 可变实参(可变实参用map收藏)
def build_profile(first, last, **var) :
    profile = {}
    profile['first'] = first
    profile['last'] = last
    for k, v in var.items() :
        profile[k] = v
    
    return profile


my_profile = build_profile('hailong', 'shi', city='shanghai', job='it')
print(my_profile)


# 导入整个模块里的所有函数
def make_pizza(size, *toppings) :
    """ pizza.py """
    print("Make " + str(size) + " pizza, need toppings below:")
    for topping in toppings :
        print(" -" + topping)


 """ test.py """
import pizza
pizza.make_pizza(15, 'a', 'b') # 需要 pizza后面跟点
pizza.make_pizza(18, 'a', 'b', 'c')


# 导入整个模块里的所有函数2     import * 版
def make_pizza(size, *toppings) :
    """ pizza.py """
    print("Make " + str(size) + " pizza, need toppings below:")
    for topping in toppings :
        print(" -" + topping)


def fun_b() :
    print("fun_b")


 """ test.py """
import pizza *
make_pizza(15, 'a', 'b') # 需要 pizza后面跟点
make_pizza(18, 'a', 'b', 'c')
fun_b()


# 导入模块里的特定函数
def make_pizza(size, *toppings) :
    """ pizza.py """
    print("Make " + str(size) + " pizza, need toppings below:")
    for topping in toppings :
        print(" -" + topping)


 """ test.py """
from pizza import make_pizza # 特定函数
from pizza import * # 导入所有函数 但是容易重名 尽量少用
make_pizza(15, 'a', 'b') # 不要要点
make_pizza(18, 'a', 'b', 'c')


# 导入模块里的特定函数  并且 指定别名
def make_pizza(size, *toppings) :
    """ pizza.py """
    print("Make " + str(size) + " pizza, need toppings below:")
    for topping in toppings :
        print(" -" + topping)


 """ test.py """
from pizza import make_pizza as mp
mp(15, 'a', 'b') # 不要要点
mp(18, 'a', 'b', 'c')


# 导入整个模块 并且 把模块 指定别名
def make_pizza(size, *toppings) :
    """ pizza.py """
    print("Make " + str(size) + " pizza, need toppings below:")
    for topping in toppings :
        print(" -" + topping)


 """ test.py """
import pizza as mn
mn.make_pizza(15, 'a', 'b') # 不要要点
mn.make_pizza(18, 'a', 'b', 'c')


# 导入类
""" xxx.py """
class A() :
    -- snip --


""" test.py """
from xxx import A
my_a = A()


# 类定义 & 访问类实例属性 & 访问类实例方法
 # class Dog(object) :   # python2.7 的做法
class Dog() :
    """ 创建小狗 """


    def __init__(self, name, age) :
        """ initialize dog """
        self.name = name
        self.age = age


    def site(self) :
        """ simulate site down """
        print(self.name.title() + " site down")


    def rollover(self) :
        """ simulate rollover """
        print(self.name.title() + " roll over")




my_dog = Dog('taotao', 26)
print("my dog name:" + my_dog.name.title())
print("my dog age:" + str(my_dog.age))
my_dog.site()
my_dog.rollover()


# 类 访问属性 修改属性接口 属性默认值
class Car() :
    """ Car Info """


    def __init__(self, make, model, year) :
        """ Initialize """
        self.make = make
        self.model = model
        self.year = year
        self.mile = 0 # 属性默认值


    def get_full_name(self) :
        """ return full name """
        full_name = "The Car info:" + self.make + " " + self.model + " " + str(self.year)
        return full_name.title()


    def display_mile(self) :
        print("The car mile:" + str(self.mile))


    def update_mile(self, new_mile) : # 接口修改属性值
        if new_mile >= self.mile :
            self.mile = new_mile
        else :
            print("You can not roll back mile")
    def inc_mile(self, new_mile) :
        self.mile += new_mile


my_car = Car('audi', 'a4', 2016)
print(my_car.get_full_name())
my_car.display_mile()
my_car.update_mile(26)
my_car.display_mile()
my_car.update_mile(24)
my_car.display_mile()
my_car.mile = 24 # 直接修改属性值
my_car.display_mile()
my_car.inc_mile(100) # 通过接口增量修改属性值
my_car.display_mile()


# 类 继承
class EleCar(Car) :
    def __init__(self, make, model, year) :
        super().__init__(make, model, year) # 调用父类的 __init__函数


my_tesla = EleCar('tesla', 'model s', 2016)
print(my_tesla.get_full_name())


# python2.7的继承
class Car(object) :
    def __init__(self, make, model, year) :
    -- snip --


class EleCar(Car) :
    def __init(self, make , model, year) :


        # super需要2个实参 将父类和子类关联起来
        super(EleCar, self).__init__(make, model, year)
        -- snip --


# 类 继承 给子类增加属性和方法 & 重写父类的方法
class EleCar(Car) :
    def __init__(self, make, model, year) :
        super().__init__(make, model, year)
        self.battery = 70


    def display_battery(self) :
        print("The car battery:" + str(self.battery))


    def display_mile(self) : # 重写父类的方法
        print("Now I am in EleCar")


my_car = Car('aodi', 'a4, 2016)
my_tesla = EleCar('tesla', 'model s', 2016)
my_car.display_mile() # 调用父类的
my_tesla.display_mile() # 调用子类的
print(my_tesla.get_full_name())
my_tesla.display_battery()


# 类的组合
class Battery() :
    
    def __init__(self, battery_size=70) :
        self.battery_size = battery_size


    def show_battery(self) :
        print("The car's batter size:" + str(self.battery_size))


    def show_go_mile(self) :
        if self.battery_size == 70 :
            range = 240
        elif self.battery_size == 85 :
            range = 360


        print("The car can go " + str(range) + " miles under batter_size:" + str(self.battery_size))




class EleCar(Car) :
    def __init__(self, make, model, year) :
        super().__init__(make, model, year)
        self.battery = Battery(85)




my_tesla = EleCar('tesla', 'model s', 2016)
my_tesla.battery.show_battery()
my_tesla.battery.show_go_mile()


# 导入单个类 (被导入模块含单个类)
""" car.py """
class Car() :
    -- snip --


""" my_car.py """
from car import Car


# 导入单个类(被导入模块含多个类)
""" car.py """
class Car() :
    -- snip --


class EleCar(Car) :
    -- snip --


""" my_car.py """
from car import EleCar


# 从一个模块导入多个类
from car import Car, EleCar


my_car = Car('Audi', 'a6', 2016)
my_car.display_mile()
my_tesla = EleCar('tesla', 'model s', 2016)
my_tesla.battery.show_battery()
my_tesla.battery.show_go_mile()


# 导入整个模块  然后用 模块名.类名 实例化类
import car


my_car = car.Car('Audi', 'a6', 2016)
my_car.display_mile()
my_tesla = car.EleCar('tesla', 'model s', 2016)
my_tesla.battery.show_battery()
my_tesla.battery.show_go_mile()


# 导入模块内的所有类  --不建议使用
from car import *


my_car = Car('Audi', 'a6', 2016)
my_car.display_mile()
my_tesla = EleCar('tesla', 'model s', 2016)
my_tesla.battery.show_battery()
my_tesla.battery.show_go_mile()


# 模块分散 各自导入
""" car.py """
    -- snip --


""" ele_car """
    -- snip ---


""" my_car.py """
from car import Car
my_car = Car('Audi', 'a6', 2016)
my_car.display_mile()


from ele_car import EleCar
my_tesla = EleCar('tesla', 'model s', 2016)
my_tesla.battery.show_battery()
my_tesla.battery.show_go_mile()


# 标准库 - collections:OrderedDict
from collections import OrderedDict


f_l = OrderedDict()
f_l['a'] = 'a100'
f_l['b'] = 'b100'
f_l['c'] = 'c100'
f_l['d'] = 'd100'
for k, v in f_l.items() :
    print(" -" + k + " " + v.title())


# 文件  读取全部内容
with open('C:/Dev/pi.txt') as file_object :
    c = file_object.read()
    print(c.rstrip()) # 删除字符串末尾的空格 不再换行


# 文件 逐行读取文件
with open('C:/Dev/pi.txt') as file_object :
    for line in file_object :
        print(line.rstrip()) # 删除字符串末尾的空格 不再换行


# 文件  读取文件行保存在list 然后在外部使用
with open('C:/Dev/pi.txt') as file_object :
    lines = file_object.readlines()


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


# 文件 拼接所有行在一起
with open('C:/Dev/pi.txt') as file_object :
    lines = file_object.readlines()


pi_string = ''
for line in lines :
    pi_string += line.strip() # 删除所有的空格


print(pi_string)
print(len(pi_string))


# 文件 只获取文件的一部分内容
with open('C:/Dev/pi.txt') as file_object :
    lines = file_object.readlines()


pi_string = ''
for line in lines :
    pi_string += line.strip() # 删除所有空格


print(pi_string[:52] + "...") # 只获取52个字节
print(len(pi_string))


# 文件 检查文件内容是否包含指定字符串
with open('C:/Dev/pi.txt') as file_object :
    lines = file_object.readlines()


pi_string = ''
for line in lines :
    pi_string += line.strip()


birth = input("Input your birthday:")
if birth in pi_string :
    print("You birth day is in")
else :
    print("You birth is not in")


# 文件  写文件
with open('C:/Dev/t.txt', 'w') as file_object :
    """ r w(写覆盖) a r+(读写) """
    file_object.write("Ha ha ha")


# 文件 写文件 加入 换行符
with open('C:/Dev/t.txt', 'w') as file_object :
    file_object.write("Ha ha ha1\n")
    file_object.write("Haha2\n")
    file_object.write("Haha3\n")


# 异常 异常码 汇总
ZeroDivisionError
FileNotFoundError


# 异常
try :
    print(5/0)
except ZeroDivisionError :
    print("Divide zero")


# 异常 else代码块
print("Enter two num, I will divide them:") 
print("Print q to exit")
while True :
    num1 = input("Fist number:")
    if num1 == 'q' :
        break
    num2 = input("Second number:")
    try :
        div = int(num1) / int(num2)
    except ZeroDivisionError :
        print("You can not divide 0")
    else :
        print("Result:" + str(div))


# 异常 FileNotFoundError
file_name = 'tt.txt'
try :
    with open(file_name) as file_object :
        content = file_object.read()
except FileNotFoundError :
    msg = "Sorry, the file " + file_name + " not found"
    print(msg)


# 文件 异常 字符串 split
try :
    with open('C:/Dev/pi.txt') as file_object :
        content = file_object.read()
except FileNotFoundError :
    msg = "File not found "
else :
    words = content.split() # words 现在是一个 list
    len = len(words)
    print("File have about " + str(len) + " Words")


# 文件 使用多个文件 pass
def count_times(file) :
    try :
        with open(file) as file_object :
            content = file_object.read()
    except FileNotFoundError :
        print("Do no find file:" + file) # pass 也可以用pass,占位符,啥都不做
    else :
        value = content.split()
        times = len(value)
        print("The file " + file + " have " + str(times) + " words")


file_list = ['ff.txt', 'C:/Dev/pi.txt']
for file in file_list :
    count_times(file)


# 文件 将数据存储为json文件
import json


numbers = [1, 2, 3, 4, 5]
with open('C:/Dev/tt.json', 'w') as file_object :
    json.dump(numbers, file_object)


# 文件 读取json文件
import json


with open('C:/Dev/tt.json') as file_object :
    numbers = json.load(file_object)


print(numbers)


# 文件&异常 函数 返回值 重构(多个小函数配合)
import json


def get_old_name() :
    filename = 'C:/Dev/name.json'
    try :
        with open(filename) as file_obj :
            username = json.load(file_obj)
    except FileNotFoundError :
        return None
    else :
        return username


def get_new_name() :
    username = input("Input your name:")
    filename = 'C:/Dev/name.json'
    with open(filename, 'w') as file_obj :
        json.dump(username, file_obj)
    return username


def greet_user() :
    user_name = get_old_name()
    if user_name :
        print("Welcome back:" + user_name + "!")
    else :
        username = get_new_name()
        print("Your new name is:" + username)
        
greet_user()


# 单元测试 函数 3个测试用例
import unittest


def get_full_name(first, last, middle='') :
    if middle :
        return first.title() + ' ' + middle.title() + ' ' + last.title() 
    else :
        return first.title() + ' ' + last.title()        


class NameTestCase(unittest.TestCase) :
    def test_name_case(self) : # 函数名必须以test开头 [测试用例1]
        full_name = get_full_name('hailong', 'shi')


        # 测试用例  通过
        self.assertEqual(full_name, 'Hailong Shi')
    
    def test_middle_case(self) : # 函数名必须以test开头 [测试用例2]
        full_name = get_full_name('hailong', 'shi', 'jack')


        # 测试用例  通过
        self.assertEqual(full_name, 'Hailong Jack Shi')


class NameTestCase2(unittest.TestCase) :
    def test_name_case(self) : # 函数名必须以test开头 [测试用例3]
        full_name = get_full_name('hailong', 'shi')


        # 测试用例  未通过
        self.assertEqual(full_name, 'hailong Shi')




unittest.main()


# 单元测试 各种断言方法
assertEqual(a, b)
assertNotEqual(a, b)
assertTrue(x)
assertFalse(x)
assertIn(x, list)
assertNotIn(x, list)


# 单元测试 类 2个测试用例
class AnoSurvey() :
    def __init__(self) :
        self.responses = []


    def add_response(self, value) :
        self.responses.append(value)


    def show_result(self) :
        for v in self.responses :
            print(" - " + v)


import unittest
class TestAnoSurvey(unittest.TestCase) :
    def setUp(self) : # 首先执行 setUp函数
        self.m_survey = AnoSurvey()
        self.m_testlist = ['english', 'chinese', 'japanese']


    def test_single_result(self) : # 单元测试1
        self.m_survey.add_response(self.m_testlist[0])
        
        self.assertIn(self.m_testlist[0], self.m_survey.responses)


    def test_three_result(self) : # 单元测试2
        for v in self.m_testlist :
            self.m_survey.add_response(v)


        for v in self.m_testlist :
            self.assertIn(v, self.m_survey.responses)


unittest.main()

猜你喜欢

转载自blog.csdn.net/helonsy/article/details/80836627