文章目录

  • Python_PS
    • Source Code
  • Python_RUA
    • Source Code
    • PIP&&Release
      • PIP
      • Release
    • FILE
      • 文件路径
        • 打开文件:用open()函数打开文件
        • 关闭文件:用close()方法关闭文件。
        • 写文件
        • 读文件
      • 二进制文件
      • CSV
        • CSV简介
        • 写CSV
        • 读CSV

Python_PS

Source Code

# Python_Study
print("------Hail Hydra------")
message = "Mission_Report:1991/12/16"
print(message)  # Python中字符串不可直接修改 不能用++name = "security level seven"
print(name)
print(name.title())
print(name.upper())
print(name.lower())first_name = "ada"
last_name = "lovelace"
full_name = first_name + " " + last_name
print(full_name)print("Hello, " + full_name.title() + "!")language = "  python  "
language = language.rstrip()
print(language)
language = language.lstrip()
print(language)print(3**2, 3 * 2, "\t")
print(3**2, 3 * 2, end=" \n")  # python默认自动换行,end=" "取消自动换行
print(3**2, 3 * 2, " ")age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1], bicycles[0])
bicycles.append("AAAA")
bicycles.insert(0, "BBBB")  # del bicycles[0]
print(bicycles)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)  # pop相当于出栈 @name.pop(a) ->删除name的0位元素
motorcycles.remove('yamaha')  # 按值删除
print(motorcycles)cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)  # 永久排序sortcars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)  # 暂时排序sorted
print(len(cars))# reverse() 反转列表magicians = ['alice', 'david', 'carolina']
for m in magicians:print(m)print(m.title() + ", that was a great trick!")for value in range(1, 5):  # range()让你能够轻松地生成一系列的数字print(value)  # 只能打印1~4numbers = list(range(1, 6))
print(numbers)
squares = []
for value in range(1, 11):square = value**2squares.append(square)
print(squares)  # min() max() sum()直接可用squares = [value**2 for value in range(1, 11)]
print(squares)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])  # 提取列表的第2~4个元素,可将起始索引指定为1,并将终止索引指定为4
print(players[-3:])  # 遍历局部
for player in players[:3]:print(player.title())
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]  # 列表复制 friend_foods = my_foods不行 类似于引用
# dimensions = (200, 50) 定义元组 类似pair<,> 内值不可变动 但可以重新初始化来修改
# &->and  ||->or  '@target' in @name -> @name中含有@target
# if @target'not in @name
# if-elif-else  Python并不要求 if-elif 结构后面必须有elsealien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])  # 字典(键—值对的集合)
new_points = alien_0['points']
# 字典是一种动态结构,可随时在其中添加键—值对。要添加键—值对,可依次指定字典名、用方括号括起的键和相关联的值。
alien_0 = {}  # 空字典
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
del alien_0['points']
favorite_languages = {'jen': 'python','sarah': 'c','edward': 'ruby','phil': 'python',
}
for name in favorite_languages.keys():  # 或for name in favorite_languagesprint(name.title()+'\t'+favorite_languages[name].title())
if 'erin' not in favorite_languages.keys():print("Erin, please take our poll!")alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:print(alien)# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))# 在字典中存储列表
pizza = {'crust': 'thick','toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " +"with the following toppings:")
for topping in pizza['toppings']:print("\t" + topping)favorite_languages = {'jen': ['python', 'ruby'],'sarah': ['c'],'edward': ['ruby', 'go'],'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():print("\n" + name.title() + "'s favorite languages are:")for language in languages:print("\t" + language.title())# 字典嵌套字典
users = {'aeinstein': {'first': 'albert','last': 'einstein','location': 'princeton',},'mcurie': {'first': 'marie','last': 'curie','location': 'paris',},}
for username, user_info in users.items():print("\nUsername: " + username)full_name = user_info['first'] + " " + user_info['last']location = user_info['location']print("\tFull name: " + full_name.title())print("\tLocation: " + location.title())for a in range(30):if a == 1:  # 注意冒号breakmessage = input("Tell me something, and I will repeat it back to you: ")
print(message)
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
height = input("How tall are you, in inches? ")
height = int(height)# while循环 python可用break
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':message = input(prompt)print(message)
active = True
active = False  # Bool型# 首先,创建一个待验证用户列表
#  和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
#  将每个经过验证的列表都移到已验证用户列表中
while unconfirmed_users:current_user = unconfirmed_users.pop()print("Verifying user: " + current_user.title())confirmed_users.append(current_user)
# 显示所有已验证的用户
print("\nThe following users have been confirmed:")
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)responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:# 提示输入被调查者的名字和回答name = input("\nWhat is your name? ")response = input("Which mountain would you like to climb someday? ")# 将答卷存储在字典中responses[name] = response# 看看是否还有人要参与调查repeat = input("Would you like to let another person respond? (yes/ no) ")if repeat == 'no':polling_active = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():print(name + " would like to climb " + response + ".")def greet_user(username):  # 函数定义前需要两个空行print("Hello, " + username.title() + "!")greet_user('jesse')  # 函数定义前后需要两个空行def describe_pet(pet_name, animal_type='dog'):"""显示宠物的信息"""print("\nI have a " + animal_type + ".")print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet('willie')  # 未指定type时按照默认参数值def get_formatted_name(first_name, last_name, middle_name=''):"""返回整洁的姓名"""if middle_name:full_name = first_name + ' ' + middle_name + ' ' + last_nameelse:full_name = first_name + ' ' + last_namereturn full_name.title()musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)  # 可选的参数# function_name(list_name[:]) 调用函数时禁止函数修改列表 将列表的副本传递给函数
# print_models(unprinted_designs[:], completed_models)def make_pizza(size, *toppings):"""概述要制作的比萨"""print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")for topping in toppings:print("- " + topping)make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
# 结合使用位置实参和任意数量实参(toppings) 放在最后def build_profile(first, last, **user_info):"""创建一个字典,其中包含我们知道的有关用户的一切"""profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key, value in user_info.items():profile[key] = valuereturn profileuser_profile = build_profile('albert', 'einstein',location='princeton', field='physics')
print(user_profile)
# 使用任意数量的关键字实参#  Python_OOP  #"""导入类"""
# 从car模块(car.py)导入Car类,ElectricCar类
#   from car import Car,ElectricCar# import car 导入整个模块,再使用句点表示法访问需要的类
#   my_beetle = car.Car('volkswagen', 'beetle', 2016)
#   print(my_beetle.get_descriptive_name())# 导入模块中的所有类(不推荐,容易引起名称冲突)
#   from module_name import *# 子类分离写成模块时需要import父类模块"""类编码风格"""
"""
类名应采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不使用下划线。
实例名和模块名都采用小写格式,并在单词之间加上下划线。
对于每个类,都应紧跟在类定义后面包含一个文档字符串。
这种文档字符串简要地描述类的功能,并遵循编写函数的文档字符串时采用的格式约定。
每个模块也都应包含一个文档字符串,对其中的类可用于做什么进行描述。
可使用空行来组织代码,但不要滥用。在类中,可使用一个空行来分隔方法;
而在模块中,可使用两个空行来分隔类。
需要同时导入标准库中的模块和你编写的模块时,先编写导入标准库模块的import语句,
再添加一个空行,然后编写导入你自己编写的模块的import语句。
在包含多条import语句的程序中,这种做法让人更容易明白程序使用的各个模块都来自何方。
"""class Car():  # 空白类def __init__(self, make, model, year):"""初始化描述汽车的属性"""self.make = makeself.model = modelself.year = yearself.odometer_reading = 0  # 新增一个带有默认初始化的属性def get_descriptive_name(self):"""返回整洁的描述性信息"""long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn long_name.title()def read_odometer(self):"""打印一条指出汽车里程的消息"""print("This car has " + str(self.odometer_reading) + " miles on it.")def update_odometer(self, mileage):"""将里程表读数设置为指定的值"""self.odometer_reading = mileagedef increment_odometer(self, miles):"""将里程表读数增加指定的量"""self.odometer_reading += milesdef fill_gas_tank(self):print("Gas tank filled successfully!")my_new_car = Car('audi', 'a4', 2016)
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(44)  # 通过方法修改属性的值
my_new_car.read_odometer()my_used_car = Car('subaru', 'outback', 2013)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()  # 通过方法对属性的值进行递增
my_used_car.fill_gas_tank()#  继承  #
class ElectricCar(Car):  # 继承类"""电动汽车的独特之处"""def __init__(self, make, model, year):"""初始化父类的属性"""super().__init__(make, model, year)# 父类也称为超类(superclass)super()将父类和子类关联起来self.battery_size = 70  # 新建属性必须跟在__init__下"""给子类定义属性(电瓶)和方法(描述属性的方法,即打印容量)"""def describe_battery(self):"""打印一条描述电瓶容量的消息"""print("This car has a " + str(self.battery_size) + "-kWh battery.")def fill_gas_tank(self):"""电动汽车没有油箱"""print("This car doesn't need a gas tank!")# 在子类中重写父类的方法与要重写的父类方法同名 Python将只关注你在子类中定义的相应方法。# 也可将电池有关的属性和方法提取出来放到另一个名为Battery的类中,并将一个Battery实例用作ElectricCar类的一个属性# class Battery():  self.battery = Battery()def get_range(self):"""打印一条消息,指出电瓶的续航里程"""if self.battery_size == 70:range = 240elif self.battery_size == 85:range = 270message = "This car can go approximately " + str(range)message += " miles on a full charge."print(message)my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
my_tesla.get_range()
#  将Battery单独写为类的时候  my_tesla.battery.get_range()"""文件和异常"""
with open('pi_digits.txt') as f_object:contents = f_object.read()print(contents)
"""
该输出唯一不同的地方是末尾多了一个空行。
因为read()到达文件末尾时返回一个空字符串,
而将这个空字符串显示出来时就是一个空行。
要删除多出来的空行,可在print语句中使用rstrip():
"""
with open('pi_digits.txt') as file_object:contents = file_object.read()print(contents.rstrip())with open('text_files/fl.txt') as fln:contents = fln.read()print(contents.rstrip())# 绝对路径
file_path = 'D:\\Center\\Code\\Python\\text_files\\fl.txt'
with open(file_path) as file_object:contents = file_object.read()print(contents.rstrip())# 逐行读取
filename = 'pi_digits.txt'
with open(filename) as file_object:for line in file_object:print(line)for line in file_object:print(line.restrip())# 创建包含文件各行内容的列表
filename = 'pi_digits.txt'
with open(filename) as file_object:lines = file_object.readlines()print(lines)
for line in lines:print(line.rstrip())  # 方法readlines()从文件中读取每一行,并将其存储在一个列表中
# print(pi_string[:52] + "...") 打印小数点后50位
message = "I really like dogs."
message.replace('dog', 'cat')
print(message.replace('dog', 'cat'))
print(message)  # 注意 replace 不会改变原 string 的内容,返回新字符串# 写入文件
filename = 'programming.doc'
with open(filename, 'w') as file_object:file_object.write("I love programming.\n")file_object.write("I love programming.\n")# 读取模式('r')、写入模式('w')、附加模式('a')或让你能够读取和写入文件的模式('r+')
# 注意 Python只能将字符串写入文本文件。要将数值数据存储到文本文件中,必须先使用函数str()将其转换为字符串格式。
# 函数write()不会在你写入的文本末尾添加换行符
# 使用write()时 如果指定的文件已经存在,Python将在返回文件对象前清空该文件# 附加模式 给文件添加内容,而不是覆盖原有的内容
with open(filename, 'a') as file_object:file_object.write("I also love finding meaning in large datasets.\n")"""异常处理"""# 依赖于try代码块成功执行的代码都应放到else代码块中# 处理ZeroDivisionError异常
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")while True:first_number = input("\nFirst number: ")if first_number == 'q':breaksecond_number = input("Second number: ")if second_number == 'q':breaktry:answer = int(first_number) / int(second_number)except ZeroDivisionError:print("You can't divide by 0!")else:print(answer)# 处理FileNotFoundError异常
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)filename = 'alice.txt'try:with open(filename, encoding='utf-8') as f:contents = f.read()
except FileNotFoundError:print(f"Sorry, the file {filename} does not exist.")# 以 f 开头,包含的{}表达式在程序运行时会被表达式的值代替
else:# Count the approximate number of words in the file.words = contents.split()    # 方法split(),它根据一个字符串创建一个单词列表(即逐单词,不含空格)num_words = len(words)print(f"The file {filename} has about {num_words} words.")"""多文件处理"""
"""
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:count_words(filename)
""""""隐藏错误信息"""def count_words(filename):"""计算一个文件大致包含多少个单词"""try:with open(filename, encoding='utf-8') as f:contents = f.read()except FileNotFoundError:passelse:words = contents.split()num_words = len(words)print(f"The file {filename} has about {num_words} words.")filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:count_words(filename)
"""使用json存储数据 JSON(JavaScript Object Notation)"""
# 使用json.dump()和json.load()# 函数json.dump()接受两个实参:要存储的数据以及可用于存储数据的文件对象
# 使用json.load()将这个列表读取到内存中
import jsonnumbers = [2, 3, 5, 7, 11, 13]filename = 'numbers.json'
with open(filename, 'w') as f:json.dump(numbers, f)
with open(filename) as f_obj:numbers = json.load(f_obj)
print(numbers)# 记忆用户姓名# 未重构版本
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 get_stored_username():"""Get stored username if available."""filename = 'username.json'try:with open(filename) as f:username = json.load(f)except FileNotFoundError:return Noneelse:return usernamedef get_new_username():"""Prompt for a new username."""username = input("What is your name? ")filename = 'username.json'with open(filename, 'w') as f:json.dump(username, f)return usernamedef greet_user():"""Greet the user by name."""username = get_stored_username()if username:print(f"Welcome back, {username}!")else:username = get_new_username()print(f"We'll remember you when you come back, {username}!")greet_user()"""
文件username.json不存在,将引发FileNotFoundError异常,将执行except代码块:提示用户输入其用户名
再使用json.dump()存储该用户名,并打印一句问候语
"""

Python_RUA

Source Code

for i in range(1,10):for j in range(1,i+1):print(i,"*",j,"=",i*j," ",end="")print("")n=eval(input("输入整数N:"))
sum=0
for i in range(n):i=i+1sum=sum+i
print("1-N 求和结果: ",sum)
s="Hive"
a=len(s)
print(a)# 输入输出函数
# input返回值是字符类型
it=eval(input("输入若干个学生成绩:"))
x=max(it)
y=min(it)
print("最高分: ",x)
print("最低分: ",y)print(abs(-23))
print(divmod(24,3))
print(pow(2,3))
print(pow(2,3,7))
print(round(2.56,1))
print(round(2.56))
print(round(2.56,0))# 字符串操作
weekid=eval(input("输入星期几(1-7):"))
weekstr="星期一星期二星期三星期四星期五星期六星期日"
pos=(weekid-1)*3
s=weekstr[pos:pos+3]
print(s)s="HelloWorld"
print(s[0:6])
print(s[0:6:2])
print(s[::-1])
print(s[6:0:-1])
print(s[:])# 字符串内置函数
# 处理函数
s="HailHydra"
len(s)
str(s)
chr(100)
ord('d')
hex(16)
oct(67)# 数据类型转换
import math
r=float(input("输入半径: "))
# 浮点型不分double float,不能写double()
c=2*math.pi*rimport math
x=eval(input("Input a number: "))
y=eval(input("Input another number: "))
print(x+y)
print(x-y)
print(x*y)
print(x/y)
# 顺序
print(3)
print(4)
print("The answer is ",end="")
print(3+4)
# 分支
import math
a = float(input())
b=float(input())
c=float(input())
h=a+b+c/2
area=math.sqrt(h*(h-a)*(h-b)*(h-c))
print("S= {:.5f}".format(area))if a<60:print("HailHydra")
# 列表
stu_infos=[['Mike',20,'USA',78],['Daisy',22,'UK',87],
['Phil',34,'China',89]]
print("{}\t{}\t{}\t{}".format('Name','Age','Address','Score'))
for i in range(3):stu_name=stu_infos[i][0]stu_age=stu_infos[i][1]stu_addr=stu_infos[i][2]stu_sco=stu_infos[i][3]print("{}\t{}\t{}\t{}".format(stu_name,stu_age,stu_addr,stu_sco))# 元组#  判断字符串是否只有字母和数字组成
alpha_lower=('a','b','c','d','e')
alpha_upper=('A',"B",'C','D','E')
num=('0','1','2','3','4') #  这里将数字转化为字符,因为输入的为字符串
alpha_num=alpha_lower+alpha_upper+num
input_str=input("Input a string :")
p=True
for i in range(len(input_str)):if input_str[i] not in alpha_num:p=Falsebreak
if p==True:print("Right")
else:print("Wrong")# 字典
d={"python":2,"Java":23}
for k in d:print(k,end=' ')print(d[k])    for k in d.values():print(k)for k in d.keys():print(k)for k in d.items():print(k)# 集合#  生成20个0-20随机数并输出其中互不相同的
import random
ls=[]
for i in range(20):ls.append(random.randint(0,20))s=set(ls)
print("Number is: ")
print(ls)
print("Unique number is: ")
print(s)# 综合# a
from random import randint
n=int(input("输入学生人数: "))
st_info=[]
for i in range(n):st_num=randint(2019010001,2019010100)st_com=randint(50,100)st_eng=randint(50,100)st_sum=st_com+st_engt=[st_num,st_com,st_eng,st_sum,1] #  初始名次均为1st_info.append(t)
'''排名次算法'''
for i in range(n-1):for j in range(i+1,n):if(st_info[i][3]>st_info[j][3]):st_info[j][4]+=1else:st_info[i][4]+=1print("以列表形式输出学生信息总表")
print(st_info)
print()print("用format方法输出学生信息总表")
print("{0:*^50}".format("学生信息总表"))
print("{:<10}\t{:<6}\t{:<6}\t{:<8}\t{:<8}".format("Code","Grade1","Grade2","Grade","Rank"))for i in range(n):print("{4:<10}\t{3:<6}\t{2:<6}\t{1:<8}\t{0:<8}".format(st_info[i][0],st_info[i][1],st_info[i][2],st_info[i][3],st_info[i][4]))''' 对比format ":"之前数字变化带来的变化  ":"前的数字要么都写(可不按顺序,可不包含所有参数序号),要么都不写,都不写的时候默认按format里从左到右的顺序print("{3:<10}\t{4:<6}\t{2:<6}\t{1:<8}\t{0:<8}".format(st_info[i][0],st_info[i][1],st_info[i][2],st_info[i][3],st_info[i][4]))##{0}对应于"age",^右对齐输出##{1}对应于"name",左对齐输出(默认)print("{0:^30}\n{1:^30}\n{1:10}".format("age","name"))print("{0:^30}\n{1:^30}\n".format("age","name"))'''
input()'''format'''
print("{:*^50}".format("学生信息总表","Hive"))
print("{0:*^50}".format("学生信息总表","Hive"))
print("{1:*^50}".format("学生信息总表","Hive"))''' output
**********************学生信息总表**********************
**********************学生信息总表**********************
***********************Hive***********************
'''#  b#  建立商品基本信息库
print("{0:*^20}".format("建立商品基本信息库"))
goods_info={}
n=int(input("输入商品数量: "))
for i in range(n):goods_num=input("输入商品编码:")goods_name=input("输入商品名称: ")goods_price=eval(input("输入商品单价: "))goods_sum=eval(input("输入商品库存数量: "))t=[goods_num,goods_name,goods_price,goods_sum]goods_info[goods_num]=t  #  商品编码是键#  查找
print("{0:*^30}".format("通过商品编码查找商品"))
t=input("输入要查找的商品编码: ")
print(goods_info.get(t,"没有找到这个商品!"))
print()#  删除商品
print("{0:*^20}".format("通过商品编码删除商品"))
t=input("输入要删除的商品编码: ")
if t in goods_info.keys():del goods_info[t]print(goos_info)print()
else:print("没有这个商品!")print()#  修改库存量
print("{0:*^30}".format("判断商品是否小于10(需要进货)"))
for i in goods_info:if(goods_info[i][3]<10):print("商品编码是{}的需要进货!".format(i))s=eval(input("输入进货数量: "))goods_info[i][3]+=s
print(goods_info)
print()'''
本学期学校开设3门选修课,一个班级有25位同学,选修情况如下:
选修1号课程的同学:李雷,张玉,王晓刚,陈红静,方向,司马清
选修2号课程额同学:施然,李芳芳,刘潇,方向,孙一航,黄煌
选修3号课程的同学:陈红静,方向,刘培良,张玉,施小冉,司马清
请编程计算:
(1)这个班有多少位学生没有选课?
(2)有多少位同学同时选修了2门课程?
(3)有多少位同学同时选修了3门课程?
(4)有多少位同学同时选修了1门课程?
'''
#利用集合统计学生选课信息
n=int(input("输入班级人数:")) #可以用赋值语句
s1={"李雷","张玉","王晓刚","陈红静","方向","司马清"} #选第一门课学生s2={"施然","李芳芳","刘潇","方向","孙一航","黄煌"} #选第二门课学生s3={"陈红静","方向","刘培良","张玉","施小冉","司马清"} #选第三门课学生#计算没有选课人数num=len(s1|s2|s3) #选课人数t1=n-num #没有选课人数print("没有选课的学生有{}人".format(t1))#计算只选两门课的人数t2_1=s1&s2-s3 #选第1,2门课不选第3门t2_2=s1&s3-s2 #选第1,3门课不选第2门t2_3=s2&s3-s1 #选第2,3门课不选第1门t2=len(t2_1)+len(t2_2)+len(t2_3) #选两门课人数print("只选两门课学生有{}人".format(t2))#同时选三门课人数t3=len(s1&s2&s3)print("同时选三门课学生有{}人".format(t3))#只选一门课人数t4_1=s1-s2-s3
t4_2=s2-s1-s3
t4_3=s3-s1-s2
t4=len(t4_1)+len(t4_2)+len(t4_3) #选一门课人数print("只选一门课学生有{}人".format(t4))
# 斐波那契前20项
fb=[1,1]
for i in range(2,18+2):fb.append(fb[i-1]+fb[i-2])
print(fb)#  牛顿迭代法求解方程f(x)=x^3-2x^2+4x+1=0根
x0=x1=0
n=0
e=0.000001
while((n==0) or abs(x0-x1)>e):x0=x1f=x0**3-2*x0**2+4*x0+1f1=3*x0**2-4*x0+4x1=x0-f/f1n=n+1print(n,x1)#  排序#  选择排序
list=[11.4,11.19,10.81,11.3,10.88,10.94]
print("原数据: ",list)
num=len(list)
for i in range(num-1):k=i  #  k为最小值for j in range(i+1,num):if list[k]>list[j]:k=jlist[i],list[k]=list[k],list[i]
print("排序后: ",list)#  插入排序
list=[11.4,11.19,10.81,11.3,10.88,10.94]
print("原数据: ",list)
num=len(list)
for i in range(1,num): #  插入次数k=list[i] # 临时记录当前元素j=i-1while j>=0: # 第二层循环表示对已排序序列从后往前遍历if list[j]>k:list[j+1]=list[j]list[j]=kj-=1
print("排序后: ",list)#  sort
number=[2,1,3]
number.sort()#排序,小——大    升序排列
print(number)number.sort(reverse=True)  #reverse=True,降序排列。默认FALSE:升序;
print(number)  b=sorted(number,reverse=True)  #有返回值,需要用一个变量进行接收,默认未认False
print(b)  b = sorted(number)  # 有返回值,需要用一个变量进行接收
print(b)
print(type(b))#  二分查找
list=[10,30,50,70,90,110,130,150,170]
x=eval(input('输入要查找的数: '))
flag=False;i=-1
low=0;high=len(list)-1while low<=high:mid=int((low+high)//2)if x==list[mid]:flag=Truei=midbreakelif x<list[mid]:high=mid-1else:low=mid+1
if flag==True:print("找到",x,"位置为",i)
else:print("未找到",x)
#  lambda
#  求负数
f=lambda x:x<0
list = [3,5,-7,4,-1,0,-9]
for i in filter(f,list):print(i)
print(list)#  全局变量
def f():global x  # 此句说明函数使用的x为全局变量xx=5print(x)return x*xx=10
print(f())
print(x)#  汉诺塔
def hanoi(n,a,b,c):if n==1:print(n,a,'->',c)else:hanoi(n-1,a,c,b)print(n,a,'->',c)hanoi(n-1,b,a,c)hanoi(4,'A','B','C')#  求[100,1000]内的回文质数
def palindrome(n):p=Falsestring1=str(n)string2=string1[-1:-(len(string1)+1):-1]#  string2=string1[::-1]if string1 == string2:p=Truereturn p
def prime(n):p=Truefor i in range(2,int(n/2)):if n % i ==0:p=Falsebreakreturn pfor n in range(100,1001):if prime(n) and palindrome(n):print(n)
def tel_menu(menu_str):  #定义菜单函数,参数print()print(menu_str)   #显示菜单内容menu_index=eval(input("请选择操作功能:0-5 "))if menu_index<0  or menu_index>6 :menu_index=1   #选错,则默认为“1--显示”。return menu_index  #返回选择结果def tel_view(tel_number): #1.通信录显示print("{:<10}{:<15}{:<20}".format("姓名","电话号码", "备注"))for tel in tel_number:print("{:<10}{:<15}{:<20}".format(tel[0],tel[1],tel[2]))def tel_find(tel_number): #2.按姓名查询name=input("联系人姓名:")if name=="":returntel_find=[]for tel in tel_number:if name==tel[0]:  #若查找到,则显示tel_find.append(tel)if len(tel_find)==0:print("查无此人")return  tel_finddef tel_append():  #3.添加联系人信息name=input("姓名:")   #输入联系人的姓名phone=input("电话号码:")remarks=input("备注:")t=[name,phone,remarks] #建立联系人信息(元组数据类型)return  t  #返回联系人信息一维元组
def tel_edit(tel_number):  #4.修改联系人信息tel=tel_find(tel_number)  #调用查找函数if len(tel)>0: #若找到,进行修改for t in tel :num=tel_number.index(t)    #查找修改的元素序号name=input("姓名:")      #修改数据phone=input("电话号码:")remarks=input("备注:")t=[name,phone,remarks]   #将联系人信息建立为一维元组数据类型tel_number[num]=t        #修改联系人信息return  tel_number   #返回修改结果
def tel_delete(tel_number):  #5.修改联系人信息if len(tel_number)==0:returntel=tel_find(tel_number)  #调用查找函数if len(tel)>0: #若找到,进行修改for t in tel :num=tel_number.index(t)    #查找修改的元素序号print(t)yn=input("是否输出(Y-删除,N-不删除):")  # 确认是否删除if yn=="Y" or yn=="y" :del(tel_number[num])return  tel_number   #返回修改结果#以下是主程序
tel_list=[] #定义存储联系人信息的列表
tel_deflaut=["机主","12345678900","本机号码"]  #数据组织为一维列表
tel_list.append(tel_deflaut) #添加本机联系人信息
menu="1--显示,2--查询,3--添加,4--修改,5--删除,0--退出" #菜单内容
while True:num=tel_menu(menu)if num==0:  #0.退出print("退出程序")breakelif num==1: #1.显示tel_view(tel_list)elif num==2: #2.查找info=tel_find(tel_list)#查找处理tel_view(info)         #查找结果输出elif num==3: #3.添加info=tel_append()     #调用添加函数,生成添加的数据tel_list.append(info) #添加联系人信息elif num==4: #4.修改info=tel_edit(tel_list)  #修改数据tel_view(info)  #显示联系人elif num==5: #5.删除info=tel_delete(tel_list)#查找处理tel_view(info)         #查找结果输出
'''
NameError:  尝试访问一个不存在的变量
TypeError:  不同类型间的无效操作
ZeroDivisionError:  除数为零
IndexError:  请求的索引超出序列的范围
KeyError:  请求一个不存在的字典键
FileNotFoundError:  找不到要打开的文件
'''#  try-except
try:  a=int(input("请输入一个整数:"))b=int(input("请输入一个整数:"))print(a/b)
except ZeroDivisionError:print("除数不能为0哦!")#  try-except-else
try:  a=int(input("请输入一个整数:"))b=int(input("请输入一个整数:"))print(a/b)
except ZeroDivisionError:print("除数不能为0哦!")
else:print("未发生异常!")#  多个except
try:  a=int(input("请输入一个整数:"))b=int(input("请输入一个整数:"))print(a/b)
except ZeroDivisionError:print("除数不能为0哦!")
except ValueError:print("请输入一个整数!")
else:print("未发生异常!")#  try…except…else…finally语句
#  不管是否发生异常、发生什么样的异常,finally后面的语句都会被执行到
try:  a=int(input("请输入一个整数:"))b=int(input("请输入一个整数:"))print(a/b)
except ZeroDivisionError:print("除数不能为0哦!")
except ValueError:print("请输入一个整数!")
else:print("未发生异常!")
finally:print("程序结束!")

PIP&&Release

PIP

Python语言第三方库依照安装方式灵活性和难易程度有3种方法:
pip工具安装
自定义安装
文件安装

PIP:
pip最常用且最高效,由Python官方提供并维护的在线第三方库安装工具。是在命令行下输入命令,命令格式为:
pip install <拟安装库名>
pip工具与操作系统也有关系,在Mac和Linux等操作系统中,pip工具几乎可以安装任何Python第三方库,在Windows操作系统中,有一些第三方库仍然需要用其他方式尝试安装。

例如:利用pip工具安装第三方库pygame,pip工具默认从网络上下载pygame库安装文件并自动安装到系统中。
在命令行下输入:pip install pygame
pip支持安装(install)、下载(download)、卸载(uninstall)、列表(list)、查看(list)、查找(search)等一系列安装和维护子命令。

pip常使用命令
pip install <拟安装库名> 功能: 下载并安装一个第三方库
pip uninstall <拟卸载库名> 功能:卸载一个已经安装的第三方库
pip list 功能:列出当前系统中已经安装的所有第三方库
pip show <拟查询库名> 功能:列出某个已经安装库的详细信息
pip download <拟下载库名> 功能:下载第三方库的安装包
pip search <拟查询关键字> 功能:联网搜索库名或摘要中关键字
pip install –U <拟更新库名> 功能:更新已经安装库的版本

自定义安装:
自定义安装指按照第三方库提供的步骤和方式安装。第三方库都有主页用于维护库的代码和文档。
以科学计算用的第三方库numpy为例,开发者维护的官方主页为:http://www.numpy.org/
浏览该网页找到下载链接,如下:
http://www.scipy.org/scipylib/download.html
进而根据指示步骤安装即可。

文件安装:

为了解决有些第三方库无法安装问题,美国加州大学尔湾分校提供了一个页面,帮助Python用户获得Windows可直接安装的第三方库文件,链接地址如下:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
进入文件目录
pip install 文件名.whl

Release

pyinstaller库简介
pyinstaller库是一个非常有用的python第三方库,它能够在Windows、Linux、Mac等操作系统下将python源文件打包,变成可直接执行的.exe文件,这个过程称为“程序发布”。需要强调的是,针对不同的操作系统,利用pyinstaller打包形成的.exe文件都不相同。

Pyinstaller命令常用参数

-h,--help 查看帮助
--clean 清理打包过程中的临时文件
-D,--onedir 默认值,生成dist目录`` -F,–onedir 在dist目录中只生成独立的打包文件 -i,<图标文件名.ico> 指定打包程序使用的图标文件`

Pyinstaller的-F选项比较常用,建议作为打包的必选项,这样会在打包后自动生成的dist目录下,只有一个.exe文件。

使用pyinstaller库打包程序时需要注意的是,首先,如果需要写文件路径,则路径中不能出现空格和英文句号“.”;源文件必须是UTF-8编码,如果编写的源程序保存为UTF-8编码形式,则可以直接执行打包命令。

#彩色圆圈图
import turtle
colors=[“red”,‘orange’,“yellow”,“green”,\
'blue','indigo','purple']
colors=colors*2
turtle.speed(12)
turtle.width(3)
turtle.bgcolor("black")
for i in range(14):c=colors[i]turtle.pencolor(c)turtle.rt(360/14)#海龟转向turtle.circle(80)#画圆
turtle.done()

将“彩色圆圈图.py”文件打包D:\>pyinstaller –F 彩色圆圈图.py

FILE

文件路径

绝对路径:从文件所在 “盘符”(根目录)开始描述文件的保存位置。
为与转义序列符反斜杠“\”区分,文件路径中的“\”需要写为“\”

路径:F:\documents\python\5-1.py
Python表述:“F:\\documents\\python\\5-1.py”
r “ F:\documents\python\5-1.py ”

相对路径:从当前工作目录开始描述文件的保存位置。
绝对路径:一般较长,引用不便

“F:\\documents\\python\\5-1.py”
相对路径:\\python\\5-1.py

按数据的组织形式不同,文件分为:
文本文件: 只含基本的文本字符(例如字母、数字、标点符号和换行符等特殊字
符),但不包含字体、大小和颜色信息,可使用记事本等软件编辑。
二进制文件:数据以二进制形式存储于文件中。除文本文件外,其它文件类型都为
二进制文件。如图像、音频、office文件等,不能用记事本编辑。

打开文件:用open()函数打开文件

语法:文件对象 = open(文件路径和名称,打开模式)
功能:打开指定的文件并返回一个文件对象,以便用该对象进行文件读写操作

Python文件打开模式

file1=open(‘E:\\python\\testfile1.txt’,‘r’)

关闭文件:用close()方法关闭文件。

语法: 文件对象 .close()

写文件

写文件时,需要以写模式打开文件,open语句用写模式打开不存在的文件可在指定位置新建一个文件

常用以下2种方法:
write()方法:将指定字符串写入文件当前插入点位置。若换行需添加‘\n’。
语法格式: 文件对象.write(字符串);

file1=open('E:\\python\\testfile1.txt', 'w’)
file1.write('欢迎学习Python语言\n’)
file1.write('The Zen of Python, by Tim Peters\n’)
file1.write('\n’)
file1.write('Beautiful is better than ugly.\n’)
file1.close()

注意:
(1)write()方法只接受字符串参数,其他类型参数需要转为字符串;
(2)write()方法本身不具有换行功能,如果需要写入后换行需要人为添加’ \n’

writelines()方法:以序列形式接受多个字符串作为参数,一次性写入多个串。
语法格式:文件对象.writelines(字符串序列)

#先将要写入的数据存入列表lst1中
lst1= ["Beautiful is better than ugly.", "Simple is better than complex.",'Flat is better than nested.']
f1 = open("E:\\python\\testfile2.txt", "w")
f1.writelines(lst1)
f1.close()

注意:
(1)writelines()方法参数可以是列表、元组等序列,序列中的元素必须为字符串类型;
(2)writelines()方法本身不具有换行功能,如果每个元素写入后换行需要人为添加’ \n’ 。

覆盖写:打开文件时用“w”,写入时会覆盖原有文件内容。文件可以不存在。
追加写:打开文件时用“a”,写入时添加到原有文件内容后面。文件必须已存在。

#  随机产生200个[0,100]之间的整数,并分行写入到文件num.txt中
import random
file1=open('E:\\python\\num.txt', 'w')
for i in range(0,200):x=random.randint(0,100)s=str(x)+'\n' file1.write(s)
file1.close()

读文件

常用以下3种方法:
read()方法
语法格式:文件对象.read([n]);
功能:读取整个文件内容或指定n个字符内容,返回一个字符串。

readline()方法
语法格式:文件对象.readline();
功能:读取文件中的一行内容(包括换行符\n),返回一个字符串。

readlines()方法
语法格式:文件对象.readlines();
功能:以行为单位读取整个文件的内容,返回一个字符串列表。

#  读取例1生成的num.txt中的数据,并输出其中的偶数
file1=open('E:\\python\\num.txt', 'r')
s = file1.readlines() #以行为单位读取整个文件
for line in s:x=eval(line.strip('\n'))  #去掉换行符if x%2==0:print(x)
file1.close()

二进制文件

#  图像复制
f_src = open('1.jpg','rb’)
content = f_src.read()f_copy = open('1-副本.jpg','wb')
f_copy.write(content)
#截取部分图片  f_copy.write(content[:-100000])f_src.close()
f_copy.close()

二进制采用二进制无格式存储,虽然表示灵活,更加节省空间,存取速度快,表示数据更为精确,不会造成有效位的丢失,但是不同的二进制文件解码方式是不同的,必须正确理解二进制文件结构和序列化规则,才能准确地理解其中内容。

#  视频复制
import time#开始时间
start_time = time.time()#以二进制方式打开视频
v_src = open('video.mp4','rb')
#读取视频中所有数据
content = v_src.read()#创建复制出来的文件
v_copy = open('video-副本.mp4','wb')
#写入
v_copy.write(content)#关闭操作
v_src.close()
v_copy.close()#结束时间
end_time = time.time()
print('耗时:',(end_time - start_time))

CSV

CSV简介

CSV,Comma-Separated Values的缩写,翻译为“逗号分隔值”。可以理解为以带逗号分隔(或其他字符)的纯文本形式存储表格数据的文件。可以用记事本,也可用Excel打开

CSV文件一般具有以下特征:

  1. 纯文本,使用某个字符集,比如ASCII、Unicode、EBCDIC或GB2312;
  2. 文件中均为字符串,不能指定字体颜色等样式,不能嵌入图像;
  3. 由记录组成,一行对应一条记录,每行开头不留空格;
  4. 每条记录被英文半角分隔符(可以是逗号、分号、制表符等)分割为字段;
  5. 每条记录都有同样的字段序列;
  6. 如果文件包含字段名,字段名写在文件第一行;

** CSV文件广泛应用于在不同程序之间转移表格数据 **
Python提供内置csv模块进行读写操作,读操作使用其中reader对象,写操作使用其中writer对象。

写CSV

import csv
'''writerow逐行写入'''
with open("E:\\python\\stu1.csv", 'w',newline='') as csv_file:writer1 = csv.writer(csv_file)writer1.writerow(['学号', '姓名', '高数', '英语', '计算机'])writer1.writerow(['201901', '张明', 83, 80, 89])writer1.writerow(['201902', '李亮', 90, 94, 97])writer1.writerow(['201903', '赵青', 75, 70, 83])#  writerow逐行写入
#  open语句中“newline=”指明写入新记录后不插入空行'''将多条记录存入列表,writerows一次写入'''
import csv
with open("E:\\python\\stu8.csv", 'w', newline='') as csv_file:writer1 = csv.writer(csv_file)ls=[['学号', '姓名', '高数', '英语', '计算机'],['201901', '张明', 83, 80, 89],['201902', '李亮', 90, 94, 97],['201903', '赵青', 75, 70, 83]]writer1.writerows(ls)'''追加写CSV文件'''
import csv
with open("E:\\python\\stu1.csv", 'a', newline='') as csv_file:writer1 = csv.writer(csv_file)writer1.writerow(['201904', '王强', '65', '69', '68'])writer1.writerow(['201905', '李莉', '76', '79', '70'])

读CSV

import csv
with open("E:\\python\\stu1.csv", 'r') as csv_file:reader1=csv.reader(csv_file)for row in reader1:print(row)

简单应用
【例】创建如图所示“通信录.csv”文件,然后在程序中查询大王的手机号、QQ号和微信号。

import csv#  将编码指定为UTF-8编码,避免中文文本读写错误
with open("d:\\通信录.csv",'r',encoding='utf-8') as txlcsv:reader = csv.reader(txlcsv)for row in reader:if row[0] == '大王':res = rowbreak
print("大王的手机号是:",res[1])
print("大王的QQ号是:",res[2])
print("大王的微信号是:",res[3])

Python_8h_Study相关推荐

最新文章

  1. TRIZ系列-创新原理-23-反馈原理
  2. Boost:测试使用大小为0的类array <>特化
  3. 让Lua支持Linq吧
  4. 云漫圈 | 革命版互联网公司虐恋大戏,周一拿去怼业务!
  5. 【Java】对JTable里的元素进行排序
  6. Java之Set接口
  7. graphx项目实战 — 航班飞行网图分析
  8. 工业智能网关,数据采集网关
  9. 计算机应用技术新生入学感想,大学新生入学心得体会范文(精选9篇)
  10. nvme协议 sata接口_NVMe/SATA SSD有啥不一样?萌新怎么选
  11. Debian9初始配置
  12. ENFP型人格的特征分析(mbti性格测试)
  13. En-Tan-Mo答社区用户问
  14. 写给初入行,刚接触Auto CAD的新人一些建议——第一期
  15. 分布式服务架构(一)---服务架构的进化史
  16. 数据结构 数组的困惑 int *p=a 到底什么意思
  17. 大三 字节搜索推荐算法实习生面经分享
  18. stm32双adc电压采集
  19. 「技术播客月」 Day 9 :未来我们还需要浏览器吗?
  20. 【网络安全】TACACS+协议

热门文章

  1. 怎么让dg连接mysql_搭建DG(data guard),及搭建过程中遇到的一些小问题
  2. 【每周CV论文推荐】初学模型量化值得阅读的文章
  3. 树莓派2B 的无线网络配置
  4. 【Kotlin】函数 ⑥ ( 函数参数为 Lambda 表达式 | Lambda 表达式作为参数的简略写法 | 唯一参数的简略写法 | 最后一个参数的简略写法 )
  5. 问题ewebeditor编辑器突破安全狗
  6. JAVA毕业设计汇美食电子商城计算机源码+lw文档+系统+调试部署+数据库
  7. php 数据采集模板,基于PHP实战帝国CMS系统二次开发(标签、模板、快速仿站、数据采集)...
  8. C++分数计算器项目设计
  9. 精通Python网络爬虫:核心技术、框架与项目实战(韦玮)pdf
  10. unity 坦克大战 (一)