diff --git a/base/alice.py b/base/alice.py new file mode 100644 index 0000000000000000000000000000000000000000..82827751f05610d156a731e82b6cd66117abc0d8 --- /dev/null +++ b/base/alice.py @@ -0,0 +1,8 @@ +filename = 'alice.txt' + +try: + with open(filename) as f_obj: + contents = f_obj.read() +except FileNotFoundError: + msg = 'Sorry, the file ' + filename + ' does not exist.' + print(msg) diff --git a/base/apostrophe.py b/base/apostrophe.py new file mode 100644 index 0000000000000000000000000000000000000000..fab7cf028de2eecd49c6a79550de8f9cf8ad29ea --- /dev/null +++ b/base/apostrophe.py @@ -0,0 +1,3 @@ +message = "Python's" +print(message) +message = 'Python's' \ No newline at end of file diff --git a/base/bicycles.py b/base/bicycles.py new file mode 100644 index 0000000000000000000000000000000000000000..3725579e0851e4a6250d5cb80ad9b9342407f8ee --- /dev/null +++ b/base/bicycles.py @@ -0,0 +1,60 @@ +bicycles = ['tom', 'jerry', 'jerry5', 'xiaohong', 'jerry5', 'xiaoming'] +print(bicycles) +# 可以直接使用, 下表从0开始 +print(bicycles[0]) +print(bicycles[0].title()) +# -1, -2,等等在bicycles[-1] 中的用法: bicycles[-1] 表示返回最后一个元素, 当然-2 就是返回倒数第二个元素 +print(bicycles[-1]) + +# 修改列表中的元素 +bicycles[1] = 'jerry2' +print(bicycles) + +# 添加元素 +# 末尾添加 +bicycles.append('xiaoqiang') +print(bicycles) +# 插入元素 +bicycles.insert(0, 'tiger') +print(bicycles) + +# 删除元素 +# del 语句 +del bicycles[0] +print(bicycles) +# pop() 弹出列表最后的元素 +pop_val = bicycles.pop() +print(bicycles) +print(pop_val) +# pop(0) 弹出指导位置元素 +pop_val2 = bicycles.pop(0) +print(bicycles) +print(pop_val2) +# remove() 根据元素的值删除元素, 只会删除列表中的第一个 +bicycles.remove('jerry5') +print(bicycles) + +# 组织列表 +# 按照字典顺序 +# sort() 永久排序, 默认正序 +cars = ['bmw', 'audi', 'toyota', 'subaru'] +print(cars) +cars.sort() +print(cars) +# 逆序 +cars.sort(reverse=True) +print(cars) +# sorted() 临时排序, 也可以使用reverse=True +print('临时排序后列表: ') +print(sorted(cars)) +print("再次查看列表: ") +print(cars) +# 倒着打印 +cars = ['bmw', 'audi', 'toyota', 'subaru'] +cars.reverse() +print(cars) + +# len() 长度 +print(len(cars)) + + diff --git a/base/birthday.py b/base/birthday.py new file mode 100644 index 0000000000000000000000000000000000000000..83befda1b4c130dce0430780753438ea73e01ebc --- /dev/null +++ b/base/birthday.py @@ -0,0 +1,5 @@ +age = 25 +print(age) +# message = "Happy" + age + "rd Birthday!" # 类型错误, python 不能直接拼接类型不同的变量, 这和java不同 +message = "Happy " + str(age) + "rd Birthday!" +print(message) \ No newline at end of file diff --git a/base/car.py b/base/car.py new file mode 100644 index 0000000000000000000000000000000000000000..b34a204e4a3f7d16ac4a2db34eb7f460cce23444 --- /dev/null +++ b/base/car.py @@ -0,0 +1,40 @@ +class Car(): + """一次模拟汽车的简单尝试""" + def __init__(self, make, model, year): + self.make = make + self.model = model + self.year = year + # 给属性指定默认值 + self.odometer_reading = 0 + + def get_descriptive_name(self): + """返回整洁的描述性信息""" + long_name = str(self.year) + ' ' + self.make + ' ' + self.model + return long_name.title() + + def read_odometer(self): + """打印一条指出汽车里程的消息""" + print('The Car has ' + str(self.odometer_reading) + ' miles on it.') + + def update_odometer(self, mileage): + """将里程表读数设置为指定的值""" + self.odometer_reading = mileage + + def increment_odometer(self, miles): + self.odometer_reading += miles + +my_new_car = Car('audi', 'a4', 2016) +print(my_new_car) +print(my_new_car.get_descriptive_name()) +my_new_car.read_odometer() +# 修改属性的值 +my_new_car.odometer_reading = 23 +my_new_car.read_odometer() + +# 通过方法修改属性的值 +my_new_car.update_odometer(30) +my_new_car.read_odometer() +# 通过方法对属性的值进行递增 +my_new_car.increment_odometer(10) +my_new_car.read_odometer() + \ No newline at end of file diff --git a/base/china.txt b/base/china.txt new file mode 100644 index 0000000000000000000000000000000000000000..cae0f51db3c79fa0c797864e6d190d4be44267ff --- /dev/null +++ b/base/china.txt @@ -0,0 +1,4 @@ +我爱你中国 + 我和我的祖国 + 台湾是祖国不可分割的一部分 + \ No newline at end of file diff --git a/base/confirmed_users.py b/base/confirmed_users.py new file mode 100644 index 0000000000000000000000000000000000000000..01a0a47b1fe6c17bc41eed42cd8b4ed989b2e466 --- /dev/null +++ b/base/confirmed_users.py @@ -0,0 +1,22 @@ +# 在列表之间移动元素 +unconfirmed_users = ['alice', 'brian', 'candace'] +confirmed_users = [] + +while unconfirmed_users: + current_user = unconfirmed_users.pop() + print('验证用户: ' + current_user.title()) + confirmed_users.append(current_user) + +# 显示所有已验证的用户 +print('\n所有已验证的用户:') +for confirmed_user in confirmed_users: + print(confirmed_user.title()) + +# 删除包含特定值的所有列表元素 +pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat'] +print(pets) + +while 'cat' in pets: + pets.remove('cat') + +print(pets) \ No newline at end of file diff --git a/base/continue.py b/base/continue.py new file mode 100644 index 0000000000000000000000000000000000000000..36a6b45ffa4b1ef3edaffe3cc6828b62a9caeb9f --- /dev/null +++ b/base/continue.py @@ -0,0 +1,9 @@ +# continue +current_number = 0 +while current_number < 10: + current_number += 1 + if current_number % 2 == 0: + continue + + print(current_number) + \ No newline at end of file diff --git a/base/datatime.py b/base/datatime.py new file mode 100644 index 0000000000000000000000000000000000000000..4c9e896fa626e429bbbc0e63e207d3807b7f9f4c --- /dev/null +++ b/base/datatime.py @@ -0,0 +1,4 @@ +from datetime import datetime + +first_date = datetime.strptime('2020-10-22 18:32:30', '%Y-%m-%d %H:%M:%S') +print(first_date) diff --git a/base/division.py b/base/division.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9da3c923c881520e79e4954f113c1a22ce0bb5 --- /dev/null +++ b/base/division.py @@ -0,0 +1,17 @@ +print('得到两个数来进行除法运算') +print("输入 'q' 退出") + +while True: + first_number = input('\n第一个数: ') + if first_number == 'q': + break + second_number = input('第二个数: ') + if second_number == 'q': + break + try: + answer = int(first_number) / int(second_number) + except ZeroDivisionError: + print("You can't divide by zero!") + else: + print(answer) + \ No newline at end of file diff --git a/base/dog.py b/base/dog.py new file mode 100644 index 0000000000000000000000000000000000000000..c05ef57c89333dc30697cb1067eb44af2d91f7d3 --- /dev/null +++ b/base/dog.py @@ -0,0 +1,33 @@ +class Dog(): + """一次模拟小狗的简单尝试""" + + def __init__(self, name, age): + """初始化属性name和age""" + self.name = name + self.age = age + + def sit(self): + """模拟小狗被命令蹲下""" + print(self.name.title() + ' 现在蹲下!') + + def roll_over(self): + """模拟小狗被命令时打滚""" + print(self.name.title() + ' 打滚!') + +# 根据类创建实例 +my_dog = Dog('哈士奇', 6) +# 访问属性 my_dog.name +print('我的狗名字是 ' + my_dog.name.title() + '.') +print('我的狗 ' + str(my_dog.age) + ' 岁了.') +# 调用方法 +my_dog.sit() +my_dog.roll_over() + +# 创建多个实例 +your_dog = Dog('泰迪', 2) +# 访问属性 your_dog.name +print('我的狗名字是 ' + your_dog.name.title() + '.') +print('我的狗 ' + str(your_dog.age) + ' 岁了.') +# 调用方法 +your_dog.sit() +your_dog.roll_over() \ No newline at end of file diff --git a/base/electric_car.py b/base/electric_car.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad13f642e4dcc79f7435b0d031d0a0e68e39f8d --- /dev/null +++ b/base/electric_car.py @@ -0,0 +1,76 @@ +class Car(): + """一次模拟汽车的简单尝试""" + def __init__(self, make, model, year): + self.make = make + self.model = model + self.year = year + # 给属性指定默认值 + self.odometer_reading = 0 + + def get_descriptive_name(self): + """返回整洁的描述性信息""" + long_name = str(self.year) + ' ' + self.make + ' ' + self.model + return long_name.title() + + def read_odometer(self): + """打印一条指出汽车里程的消息""" + print('The Car has ' + str(self.odometer_reading) + ' miles on it.') + + def update_odometer(self, mileage): + """将里程表读数设置为指定的值""" + self.odometer_reading = mileage + + def increment_odometer(self, miles): + self.odometer_reading += miles + + def fill_gas_tank(self): + """普通汽车有油箱""" + print('This Car need a gas tank!') + +class Battery(): + """一次模拟电动汽车电瓶的简单尝试""" + def __init__(self, battery_size=70): + """初始化电瓶属性""" + self.battery_size = battery_size + + def describe_battery(self): + """打印一条描述电瓶容量的消息""" + print('This Car has a ' + str(self.battery_size) + '-kwh battery.') + + def get_range(self): + """打印一条消息, 指出电瓶的续航里程""" + if self.battery_size == 70: + range = 240 + elif self.battery_size == 85: + range= 270 + + message = 'This car can go approximately ' + str(range) + ' miles on a full charge.' + print(message) + + +class ElectricCar(Car): + """ + 电动汽车的独特之处 + """ + def __init__(self, make, model, year): + """ + 初始化父类的属性 + 再初始化电动汽车特有的属性 + """ + super().__init__(make, model, year) + # 将实例用作属性 + self.battery = Battery() + + def fill_gas_tank(self): + """电动汽车没有油箱""" + print('This Car doesn‘s need a gas tank!') + +my_tesla = ElectricCar('tesla', 'model s', 2016) +print(my_tesla.get_descriptive_name()) +# 测试 给子类定义属性和方法 +# my_tesla.describe_battery() +# 测试 重写父类的方法 +my_tesla.fill_gas_tank() +# 测试 将实例用作属性 +my_tesla.battery.describe_battery() +my_tesla.battery.get_range() \ No newline at end of file diff --git a/base/error.py b/base/error.py new file mode 100644 index 0000000000000000000000000000000000000000..72b0e0e20bcac8b15e92dacd2d189b7f4c81a76c --- /dev/null +++ b/base/error.py @@ -0,0 +1,4 @@ +try: + print(5/0) +except ZeroDivisionError: + print("You can't divide by zero!") \ No newline at end of file diff --git a/base/even_or_odd.py b/base/even_or_odd.py new file mode 100644 index 0000000000000000000000000000000000000000..34263b526e97deb7b20cf9b65d54e1f9afce5ca2 --- /dev/null +++ b/base/even_or_odd.py @@ -0,0 +1,7 @@ +number = input('输入一个数, 我会告诉你是偶数还是奇数: ') +number = int(number) + +if number % 2 == 0: + print('\nnumber ' + str(number) + ' 是偶数') +else: + print('\nnumber ' + str(number) + ' 是奇数') diff --git a/base/favorite_languages.py b/base/favorite_languages.py new file mode 100644 index 0000000000000000000000000000000000000000..53e0bb87ca33a4c4e3ff933bfde5971bad76066e --- /dev/null +++ b/base/favorite_languages.py @@ -0,0 +1,11 @@ +from collections import OrderedDict + +favorite_languages = OrderedDict() + +favorite_languages['jen'] = 'python' +favorite_languages['sarah'] = 'c' +favorite_languages['edward'] = 'ruby' +favorite_languages['phil'] = 'python' + +for name, languages in favorite_languages.items(): + print(name.title() + "'s favorite languages is " + languages.title() + '.') \ No newline at end of file diff --git a/base/file_reader.py b/base/file_reader.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa0f1ed1ba3b9baf31abd5df50f9d59c2b91af7 --- /dev/null +++ b/base/file_reader.py @@ -0,0 +1,41 @@ +""" +1、打开文件: open() ,参数是文件的名称 +""" +# 读取整个文件 +with open('china.txt') as file_object: + contents = file_object.read() + print(contents) + # rstrip() 去除文本末尾空行 + print(contents.rstrip()) + +print('==================') +# 逐行读取 +filename = 'china.txt' + +with open(filename) as file_object: + print(file_object) + for line in file_object: + # 文件中的换行符也会读取出来 + print(line) + +print('==================') + +# 创建一个包含文件各行内容的列表 +# readlines() 表示读取文件中的每一行并将其储存在列表中 +with open(filename) as file_object: + lines = file_object.readlines() + +for line in lines: + print(line.rstrip()) +print('==================') +# 简单实用文件的内容 +with open(filename) as file_object: + lines = file_object.readlines() + +c_str = '' +for line in lines: + c_str += line.rstrip() + +print(c_str) +print(len(c_str)) + diff --git a/base/for.py b/base/for.py new file mode 100644 index 0000000000000000000000000000000000000000..8c768901f71bbd1e0faabcc07befcfea5fd436e7 --- /dev/null +++ b/base/for.py @@ -0,0 +1,77 @@ +# 遍历 for +names = ['name1', 'name3', 'name2'] +for name in names: + print(name) + + +# 数值列表 +# 函数 range() 范围左闭右开 +for value in range(1,10): + print(value) + + +# 使用range() 创建数字列表 +numbers = list(range(1,6)) +print(numbers) + +# 创建一个数值列表, 包含1-10 的平方 +squares = [] +for value in range(1,11): + square = value**2 + squares.append(square) + +print(squares) + +# 统计计算 +digits = [1,2,3,4,5,6,7,8,9,0] +print(min(digits)) +print(max(digits)) +print(sum(digits)) + +# 列表解析 +# 前面 生成列表squares需要好几行代码, 这里用下列表解析 +squares = [value**2 for value in range(1,11)] +print(squares) + +# 使用列表的一部分- 切片 +players = ['a','b','c','d','e','f','g'] +print(players[0:3]) +print(players[1:4]) +print(players[:4]) # 不指定, 从列头开始 +print(players[2:]) # 不指定, 到列尾 +print(players[-3:]) # 返回最后3个 + +# 遍历切片 +for player in players[:3]: + print(player) + +# 复制列表 +my_foofs = ['pizza', 'falafel', 'carrot cake'] +friend_foods = my_foofs[:] +my_foofs.append('cannoli') +friend_foods.append('ice cream') +print("我喜欢的食物是: ") +print(my_foofs) +print('\n我朋友喜欢的食物是: ') +print(friend_foods) +# 上面是使用切片来复制的列表, 如果不使用切片呢? 直接friend_foods = my_foofs 这样是不行的, 这种做法是将my_foofs 赋值给了friend_foods, 这两个指向的是同一个列表 + +# 元祖 不可变 +dimensions = (200, 500) +print(dimensions) +print(dimensions[0]) +print(dimensions[1]) +# dimensions[0] = 300 不能修改, 会报错 +# 遍历元祖 +for dimension in dimensions: + print(dimension) + +# 虽然元祖不能修改, 但是可以给存储元祖的变量赋值一个新的元祖 +print('original: ') +for dimension in dimensions: + print(dimension) + +print('modified: ') +dimensions = (100, 200) +for dimension in dimensions: + print(dimension) \ No newline at end of file diff --git a/base/hello_world.py b/base/hello_world.py new file mode 100644 index 0000000000000000000000000000000000000000..16c3c89821909707e264ca18c088b07ad246aa94 --- /dev/null +++ b/base/hello_world.py @@ -0,0 +1,5 @@ +message = "hello python world!" +print(message) + +message = "python 改变世界" +print(message) \ No newline at end of file diff --git a/base/if.py b/base/if.py new file mode 100644 index 0000000000000000000000000000000000000000..8e7388afc533eabcc06388e52d9dc6d468552e8d --- /dev/null +++ b/base/if.py @@ -0,0 +1,48 @@ +cars = ['bmw', 'audi', 'toyota', 'subaru'] +for car in cars: + if car == 'bmw': + print(car.upper()) + else: + print(car.title()) + +print('--------------') +# 检查是否相等 (区分大小写) +car = 'Audi' +print(car == 'audi') +# 不相等 +print(car != 'audi') + +print('--------------') + +# 比较数字 +age = 19 +print(age == 19) +print(age != 19) +print(age < 21) +print(age <= 21) +print(age > 21) +print(age >= 21) +print('--------------') +# 检查多个条件 +# and 同时成立; or 至少一个满足 +print(age > 10 and age < 19) +print(age > 10 or age < 19) +print('--------------') + +# 是否包含 +# in 包含; not in 不包含 +users = ['a001', 'a002', 'a003'] +print('a003' in users) +print('a004' not in users) + +# 布尔表达式 +status1 = True +status2 = False + +# 确定列表不是空的 +cars = [] +if cars: + print("cars is not null") +else: + print("cars is null") + diff --git a/base/language_survey.py b/base/language_survey.py new file mode 100644 index 0000000000000000000000000000000000000000..326ede30e696e74bb7e7fbc384bb8b4b8da9426c --- /dev/null +++ b/base/language_survey.py @@ -0,0 +1,18 @@ +from survey import AnonymousSurvey + +# 定义一个问题, 并创建一个表示调查的AnonymousSurvey 对象 +question = "What language did you first learn to speak?" +my_survey = AnonymousSurvey(question) + +# 显示问题并存储答案 +my_survey.show_question() +print("Enter 'q' at any time to quit.\n") +while True: + response = input("language: ") + if response == 'q': + break + my_survey.store_response(response) + +# 显示调查结果 +print("\nThank you to everyone who participated in the survey!") +my_survey.show_results() \ No newline at end of file diff --git a/base/making_pizzas.py b/base/making_pizzas.py new file mode 100644 index 0000000000000000000000000000000000000000..0e35a0057d77c392f5b20144f98a8609adcfa930 --- /dev/null +++ b/base/making_pizzas.py @@ -0,0 +1,15 @@ +# 导入整个模块 +import pizza +# 导入特定函数 +from pizza import make_pizza +# 使用as给函数指定别名 +from pizza import make_pizza as mp +# 使用as给模块指定别名 +import pizza as p +# 导入模块中所有函数 +from pizza import * + +pizza.make_pizza(16, 'green peppers', 'mushrooms') +make_pizza(16, 'green peppers', 'mushrooms') +mp(16, 'green peppers', 'mushrooms') +p.make_pizza(16, 'green peppers', 'mushrooms') \ No newline at end of file diff --git a/base/mountain_poll.py b/base/mountain_poll.py new file mode 100644 index 0000000000000000000000000000000000000000..e69666d36db7e34fb59623a7c54e8e488141aaaf --- /dev/null +++ b/base/mountain_poll.py @@ -0,0 +1,17 @@ +# 使用用户输入来填充字典 +responses = {} + +polling_active = True + +while polling_active: + name = input('\n你名字是什么? ') + response = input('你想爬哪一座山? ') + responses[name] = response + + repeat = input('是否还有其他人需要参与调查? (yes/no)') + if repeat == 'no': + polling_active = False + +# 打印结果 +for name, response in responses.items(): + print(name + '喜欢爬 ' + response + '.') \ No newline at end of file diff --git a/base/my_car.py b/base/my_car.py new file mode 100644 index 0000000000000000000000000000000000000000..cb247adee9812682721bf794e6b8e51fe1efb856 --- /dev/null +++ b/base/my_car.py @@ -0,0 +1,10 @@ +# 导入单个类 +from car import Car + +my_new_car = Car('audi', 'a4', 2016) +print(my_new_car) +print(my_new_car.get_descriptive_name()) +my_new_car.read_odometer() +# 修改属性的值 +my_new_car.odometer_reading = 23 +my_new_car.read_odometer() diff --git a/base/my_electric_car.py b/base/my_electric_car.py new file mode 100644 index 0000000000000000000000000000000000000000..524664690900b28442c6c93abf495a62cedcf03b --- /dev/null +++ b/base/my_electric_car.py @@ -0,0 +1,18 @@ +# 从一个模块中导入多个类 +from electric_car import ElectricCar, Car +# 导入整个模块 需要使用 模块名. +# import electric_car +# 导入模块中所有的类 +# from electric_car import * +my_new_car = Car('audi', 'a4', 2016) +print(my_new_car.get_descriptive_name()) + +my_tesla = ElectricCar('tesla', 'model s', 2016) +print(my_tesla.get_descriptive_name()) +# 测试 给子类定义属性和方法 +# my_tesla.describe_battery() +# 测试 重写父类的方法 +my_tesla.fill_gas_tank() +# 测试 将实例用作属性 +my_tesla.battery.describe_battery() +my_tesla.battery.get_range() \ No newline at end of file diff --git a/base/name_function.py b/base/name_function.py new file mode 100644 index 0000000000000000000000000000000000000000..1a0b0d2b195baaf175a1a017b33cc71f2ead2da5 --- /dev/null +++ b/base/name_function.py @@ -0,0 +1,7 @@ +def get_formatted_name(first, last, middle=''): + """生成整洁的姓名""" + if middle: + full_name = first + ' ' + middle + ' ' + last + else: + full_name = first + ' ' + last + return full_name.title() \ No newline at end of file diff --git a/base/names.py b/base/names.py new file mode 100644 index 0000000000000000000000000000000000000000..e91380e606fe15d478cfb559198de303b81f3189 --- /dev/null +++ b/base/names.py @@ -0,0 +1 @@ +from name_function import get_formatted_name diff --git a/base/pizza.py b/base/pizza.py new file mode 100644 index 0000000000000000000000000000000000000000..17e37423ab90287954bb04a2d533aeb0afd568ee --- /dev/null +++ b/base/pizza.py @@ -0,0 +1,3 @@ +def make_pizza(size, *toppings): + print(size) + print(toppings) \ No newline at end of file diff --git a/base/programming.txt b/base/programming.txt new file mode 100644 index 0000000000000000000000000000000000000000..c85df058c4913bbd88f3747415cfba44e3c4fbaf --- /dev/null +++ b/base/programming.txt @@ -0,0 +1,4 @@ +我喜欢编程. +我喜欢创建一个新的游戏. +我喜欢python. +我喜欢java. \ No newline at end of file diff --git a/base/remember_me.py b/base/remember_me.py new file mode 100644 index 0000000000000000000000000000000000000000..c6192767d5aff5b60182256ffb4b82931f26ac86 --- /dev/null +++ b/base/remember_me.py @@ -0,0 +1,61 @@ +import json + +# filename = 'username.json' +# try: +# with open(filename) as f_obj: +# username = json.load(f_obj) +# except FileNotFoundError: +# username = input('What is your name? ') +# with open(filename, 'w') as f_obj: +# json.dump(username, f_obj) +# print("We'll remember you when you come back, " + username + "!") +# else: +# print("Welcome back, " + username + "!") + +# 重构上面注释掉的代码 +# def greet_user(): +# """问候用户, 并指出其名字""" +# filename = 'username.json' +# try: +# with open(filename) as f_obj: +# username = json.load(f_obj) +# except FileNotFoundError: +# username = input('What is your name? ') +# with open(filename, 'w') as f_obj: +# json.dump(username, f_obj) +# print("We'll remember you when you come back, " + username + "!") +# else: +# print("Welcome back, " + username + "!") + +# greet_user() + +# 继续重构 +def get_stored_username(): + """如果存了用户, 就获取它""" + filename = 'username.json' + try: + with open(filename) as f_obj: + username = json.load(f_obj) + except FileNotFoundError: + return None + else: + return username + +def get_new_username(): + """提示用户输入用户名""" + username = input('What is your name? ') + filename = 'username.json' + with open(filename, 'w') as f_obj: + json.dump(username, f_obj) + return username + +def greet_user(): + """问候用户, 并指出其名字""" + username = get_stored_username() + if username: + print("Welcome back, " + username + "!") + else: + username = get_new_username() + print("We'll remember you when you come back, " + username + "!") + +greet_user() \ No newline at end of file diff --git a/base/simple_message.py b/base/simple_message.py new file mode 100644 index 0000000000000000000000000000000000000000..4cdf3b73d16dbbd31f8f01050622b0beed938800 --- /dev/null +++ b/base/simple_message.py @@ -0,0 +1,20 @@ +name = "ada lovelace" +print(name.title()) # Ada Lovelace 首字母大写 + +name2 = "Ada lovelace" +print(name2.upper()) +print(name2.lower()) + +first_name = "liu" +last_name = "dehua" +full_name = first_name + " " + last_name +print(full_name) + +print("\t制表符") +print("换行\n换行") + +favorite_language = ' python ' +print(favorite_language) +print(favorite_language.rstrip()) # 去掉后面空格 +print(favorite_language.lstrip()) # 去掉前面空格 +print(favorite_language.strip()) # 去掉前后面空格 \ No newline at end of file diff --git a/base/survey.py b/base/survey.py new file mode 100644 index 0000000000000000000000000000000000000000..8a16749796e703d0c1b4fd86444e1d0dd71d7002 --- /dev/null +++ b/base/survey.py @@ -0,0 +1,20 @@ +class AnonymousSurvey(): + """收集匿名调查问卷的答案""" + def __init__(self, question): + """存储一个问题, 并为存储答案做准备""" + self.question = question + self.responses = [] + + def show_question(self): + """显示调查问卷""" + print(self.question) + + def store_response(self, new_response): + """存储单份调查答卷""" + self.responses.append(new_response) + + def show_results(self): + """显示收集到的所有答卷""" + print('Survey results: ') + for response in self.responses: + print('- ' + response) \ No newline at end of file diff --git a/base/test_name_function.py b/base/test_name_function.py new file mode 100644 index 0000000000000000000000000000000000000000..9479a4f04273f8fbe566fc6ebd4adcb4ccc69a17 --- /dev/null +++ b/base/test_name_function.py @@ -0,0 +1,17 @@ +import unittest +from name_function import get_formatted_name + +class NamesTestCase(unittest.TestCase): + """测试name_function.py""" + + def test_first_last_name(self): + """能够正确地处理像Janis Joplin这样的姓名吗?""" + formatted_name = get_formatted_name('janis', 'joplin') + self.assertEqual(formatted_name, 'Janis Joplin') + + def test_first_middle_last_name(self): + """能够正确地处理像Wolfgang Amadeus Mozart这样的姓名吗?""" + formatted_name = get_formatted_name('wolfgang', 'mozart', 'amadeus') + self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart') + +unittest.main() \ No newline at end of file diff --git a/base/test_survey.py b/base/test_survey.py new file mode 100644 index 0000000000000000000000000000000000000000..bef589b2d9c4cc3dfc30c3f12e25e898d3e90d5d --- /dev/null +++ b/base/test_survey.py @@ -0,0 +1,45 @@ +import unittest +from survey import AnonymousSurvey + +class TestAnonymousSurvey(unittest.TestCase): + """针对AnonymousSurvey的测试""" + + # def test_store_single_response(self): + # """测试单个答案会被妥善的存储""" + # question = "What language did you first learn to speak?" + # my_survey = AnonymousSurvey(question) + # my_survey.store_response('English') + + # self.assertIn("English", my_survey.responses) + + # def test_store_three_responses(self): + # """测试三个答案会被妥善地存储""" + # question = "What language did you first learn to speak?" + # my_survey = AnonymousSurvey(question) + # responses = ['English', 'Spanish', 'Mandarin'] + # for response in responses: + # my_survey.store_response(response) + + # for response in responses: + # self.assertIn(response, my_survey.responses) + + def setUp(self): + """创建一个调查对象和一组答案, 供使用的测试方法使用""" + question = "What language did you first learn to speak?" + self.my_survey = AnonymousSurvey(question) + self.responses = ['English', 'Spanish', 'Mandarin'] + + def test_store_single_response(self): + """测试单个答案会被妥善的存储""" + self.my_survey.store_response(self.responses[0]) + self.assertIn(self.responses[0], self.my_survey.responses) + + def test_store_three_responses(self): + """测试三个答案会被妥善地存储""" + for response in self.responses: + self.my_survey.store_response(response) + + for response in self.responses: + self.assertIn(response, self.my_survey.responses) + +unittest.main() \ No newline at end of file diff --git a/base/tree.py b/base/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..bad2971b3b385e3978fc5d08bd43469fa240c825 --- /dev/null +++ b/base/tree.py @@ -0,0 +1,61 @@ +from turtle import * + +# 设置色彩模式是RGB: +colormode(255) + +lt(90) + +lv = 14 +l = 120 +s = 45 + +width(lv) + +# 初始化RGB颜色: +r = 0 +g = 0 +b = 0 +pencolor(r, g, b) + +penup() +bk(l) +pendown() +fd(l) + +def draw_tree(l, level): + global r, g, b + # save the current pen width + w = width() + + # narrow the pen width + width(w * 3.0 / 4.0) + # set color: + r = r + 1 + g = g + 2 + b = b + 3 + pencolor(r % 200, g % 200, b % 200) + + l = 3.0 / 4.0 * l + + lt(s) + fd(l) + + if level < lv: + draw_tree(l, level + 1) + bk(l) + rt(2 * s) + fd(l) + + if level < lv: + draw_tree(l, level + 1) + bk(l) + lt(s) + + # restore the previous pen width + width(w) + +speed("fastest") + +draw_tree(l, 4) + +done() \ No newline at end of file diff --git a/base/username.json b/base/username.json new file mode 100644 index 0000000000000000000000000000000000000000..2d049546e3ec47ef7f2e0c5f0e7b2da1b95cc67e --- /dev/null +++ b/base/username.json @@ -0,0 +1 @@ +"wu" \ No newline at end of file diff --git a/base/while.py b/base/while.py new file mode 100644 index 0000000000000000000000000000000000000000..63c3ed60656fa6e761779e0d6755d5c059063436 --- /dev/null +++ b/base/while.py @@ -0,0 +1,16 @@ +current_number = 1 +while current_number <=5: + print(current_number) + current_number += 1 + +# break +prompt = '\n请输入你喜欢的城市名称:' +prompt += '\n输入 "quit" 退出 ' +while True: + city = input(prompt) + + if city == 'quit': + break + else: + print('我喜欢去 ' + city + '!') + diff --git a/base/write_message.py b/base/write_message.py new file mode 100644 index 0000000000000000000000000000000000000000..007f5873c9b268bbb24c33ea0114ea99b10c51f4 --- /dev/null +++ b/base/write_message.py @@ -0,0 +1,13 @@ +filename = 'programming.txt' + +# w 表示写入模式, 还有 r 读取模式, a 附加模式, r+读取和写入文件的模式, 省略模式实参,默认为只读 +with open(filename, 'w') as file_object: + # 多条语句可以写入多行 + file_object.write('我喜欢编程.\n') + file_object.write('我喜欢创建一个新的游戏.\n') + +# 附加到文件, 就是给文件添加内容, 而不是覆盖 +with open(filename, 'a') as file_object: + # 多条语句可以写入多行 + file_object.write('我喜欢python.\n') + file_object.write('我喜欢java.') \ No newline at end of file diff --git "a/base/\347\254\2547\347\253\240 \347\224\250\346\210\267\350\276\223\345\205\245\345\222\214while\345\276\252\347\216\257.py" "b/base/\347\254\2547\347\253\240 \347\224\250\346\210\267\350\276\223\345\205\245\345\222\214while\345\276\252\347\216\257.py" new file mode 100644 index 0000000000000000000000000000000000000000..8f50859f6f6efa6a36b1d889418818aa772dae4b --- /dev/null +++ "b/base/\347\254\2547\347\253\240 \347\224\250\346\210\267\350\276\223\345\205\245\345\222\214while\345\276\252\347\216\257.py" @@ -0,0 +1,6 @@ +# input() +message = input("请输入你的名称: ") +print('hello ' + message) +age = input("请输入你的年龄: ") +age = int(age) +print(age) \ No newline at end of file diff --git "a/base/\347\254\2548\347\253\240 \345\207\275\346\225\260.py" "b/base/\347\254\2548\347\253\240 \345\207\275\346\225\260.py" new file mode 100644 index 0000000000000000000000000000000000000000..34a7f6549ec3d1b69416368b8fc81af228f81ea4 --- /dev/null +++ "b/base/\347\254\2548\347\253\240 \345\207\275\346\225\260.py" @@ -0,0 +1,119 @@ +# 定义函数 +def greet_user(): + """文档注释, 描述此函数的功能""" + print("hello") + +greet_user() + +# 向函数传递信息 +def greet_user(username): + """显示简单的问候语""" + print("Hello, " + username.title() + "!") + +greet_user('tom') + + +# 位置实参 +def describe_pet(animal_type, pet_name): + """显示宠物的信息""" + print("我的 " + animal_type + ' 的名字是 ' + pet_name) + +describe_pet('狗', '小黄') +describe_pet('猫', '小黑') + +# 关键字实参 +describe_pet(pet_name='小红', animal_type='鸡') + +# 默认值 默认值放在后面 +def describe_pet2(pet_name, animal_type='dog'): + """显示宠物的信息""" + print("我的 " + animal_type + ' 的名字是 ' + pet_name) + +describe_pet2(pet_name='小黄') +describe_pet2('大黄') +describe_pet2('大黄2', '狗') + +# 默认值 默认值放在前面 SyntaxError: non-default argument follows default argument 会报错 +# def describe_pet3(animal_type='dog', pet_name): +# """显示宠物的信息""" +# print("我的 " + animal_type + ' 的名字是 ' + pet_name) + +# 返回值 +def get_formatted_name(frist_name, last_name): + """返回整洁的姓名""" + full_name = frist_name + ' ' + last_name + return full_name.title() + +# 函数调用 +musician = get_formatted_name('jimi', 'hendrix') +print(musician) + +# 返回字典 +def build_person(frist_name, last_name): + """返回一个字典, 其中包含一个人的信息""" + person = {'first': frist_name, 'last': last_name} + return person + +musician = build_person('jimi', 'hendrix') +print(musician) + +# 在函数中修改列表 +def print_models(unprinted_designs, completed_models): + """ + 模拟打印每个设计, 直到没有末打印的设计为止 + 打印每个设计后, 都将其移到列表completed_models中 + """ + + while unprinted_designs: + current_design = unprinted_designs.pop() + + # 模拟根据设计制作3D打印模型的过程 + print('打印 模型: ' + current_design) + completed_models.append(current_design) + +def show_completed_models(completed_models): + """显示打印好的所有模型""" + print('\n') + for completed_model in completed_models: + print(completed_model) + +unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron'] +completed_models = [] +print('打印前 未打印的列表: ') +print(unprinted_designs) +# print_models(unprinted_designs, completed_models) +# unprinted_designs[:] 这个表示 unprinted_designs 列表的副本, 不会改变原来unprinted_designs的数据 +print_models(unprinted_designs[:], completed_models) +show_completed_models(completed_models) + +print('打印后 未打印的列表: ') +print(unprinted_designs) + +# 传递任意参数的实参 *toppings +def make_pizza(*toppings): + print(toppings) + +# 看到打印结果 看打印的结果实际上是 使用元祖来存储 任意数量的实参的 +make_pizza('peperoni') +make_pizza('mushrooms', 'green peppers', 5) + +# 使用位置实参和任意数量实参 +def make_pizza(size, *toppings): + print(size) + print(toppings) + +make_pizza(16, 'green peppers', 'mushrooms') + +# 使用任意数量的关键字实参 +def build_profile(first, last, **user_info): + """创建一个字典,包含我们知道的有关用户的一切""" + profile = {} + profile['frist_name'] = first + profile['last_name'] = last + for key, value in user_info.items(): + profile[key] = value + return profile + +user_profile = build_profile('albert', 'einstein', location='princeton', field='physics') +print(user_profile) + \ No newline at end of file