Twelve Python programming questions that are essential for freshmen, coding conquers everything (bushi)

1. Calculate file size

import os
def get_size(path):
    size = 0
    l = [path]
    while l:
        path = l.pop()
        lst = os.listdir(path)
        for name in lst:
            son_path = os.path.join(path,name)
            if os.path.isfile(son_path):
                size += os.path.getsize(son_path)
            else:
                l.append(son_path)
    return size

size = get_size(r'D:\s14\算法')
print(size)

Second and third level menu

l = [menu]
while l:
    for k in l[-1]:
        print(k)
    key = input('>>>')
    if key.upper() == 'B':
        l.pop()
    elif key.upper() == 'Q':
        l.clear()
    elif l[-1].get(key):
        l.append(l[-1][key])

3. File monitoring

def func():
    with open('test.txt', 'r+', encoding='utf-8') as f:
        while 1:
            lens = f.readline()
            if lens:
                yield lens
t = func()
for j in t:
    print(j)

4. Send red envelopes

import random

def rea_pac(money,num):
    ret = random.sample(range(1,money*100),num-1)
    print(ret)
    ret.sort()
    ret.insert(0,0)
    ret.append(money*100)
    for i in range(len(ret)-1):
        value = ret[i+1] - ret[i]
        yield value/100
g = rea_pac(200,10)
for i in g:
    print(i)

5. Asking for directions recursively

lis = ['alex','wusir','yuanhao','linhaifeng','henry']

def inner(name):
    if len(name) == 0:
        return '没有找到路'
    res = lis.pop(0)
    if res == 'henry':
        return '%s说:我知道老男孩就在沙河地铁站附近'%res
    print('hi美男%s敢问路在何方'%res)
    print('%s回答道,我也不知道,我帮你问问%s'%(res,lis))
    f = inner(lis)
    return f
print(inner(lis))

After finding the way, the result will be returned to the previous caller 'linhaifeng'
'linhaifeng' will return the result to the previous caller 'yuanhao'...
and finally the result will be returned to the original caller inner

6. Human-dog war

import random
import time

Define a person's class

class Person:
    # 定义人的静态属性
    def __init__(self,name,hp,ad,sex):
        self.name = name
        self.ad = ad
        self.hp = hp
        self.sex = sex
    # 定义人的方法
    def da(self,dog):
        yy = random.randint(1,self.ad)
        dog.hp -= yy
        print('%s使用%s,打了%s,%s掉了%s点血'%(self.name,arms.name,dog.name,dog.name,yy))
        if dog.hp < 50:
            print("{}使用终极必杀技{}".format(dog.name,arms.skill()))

Define a dog class

class Dog:
    # 定义狗的静态属性
    def __init__(self,name,hp,ad,kind):
        self.name = name
        self.hp = hp
        self.ad = ad
        self.kind = kind
    # 定义狗的方法
    def yao(self,person):
        uu = random.randint(1,self.ad)
        person.hp -= uu
        print('%s咬了%s,%s掉了%s点血' % (self.name, person.name, person.name,uu))
        if person.hp < 50:
            print("{}使用终极必杀技{}".format(person.name,arms.skill()))

Define a weapon class

class Arms:
    def __init__(self,name,hp,ad):
        self.name = name
        self.hp = hp
        self.ad = ad
    # 定义一个武器的技能
    def skill(self):
        li = ['飞龙在天','乾坤大挪移','九阳神功']
        f = random.choice(li)
        return f
arms = Arms('铁锹',3000,2000)
henry = Person('henry',500,30,'男')
dog = Dog('大黄',300,30,'哈士奇')
c = 1
while dog.hp > 0:

    print('第{}回合'.format(c))
    dog.yao(henry)
    henry.da(dog)
    time.sleep(1)
    c +=1

7. Calculator

import re
express = '1-2*((60-30+(9-2*5/3+7/3*99/4*2998+10*568/14)*(-40/5))-(-4*3)/(16-3*2))'
express = express.replace(' ','')

calculate

def cout(exp):
    if '*' in exp:
        a,b = exp.split('*')
        return str(float(a) * float(b))
    else:
        a, b = exp.split('/')
        return str(float(a) / float(b))

Symbol management of expressions turns ++ into +, – into –, ± into –, and –+ into –.

def format_exp(exp):
    exp = exp.replace('++','+')
    exp = exp.replace('+-','-')
    exp = exp.replace('--','+')
    exp = exp.replace('-+','-')
    return exp

Calculate all multiplications and divisions

def cal_no(res):
    while True:
        chengshu = re.search('\d+\.?\d*[*/]-?\d+\.?\d*', res)  # (9-2*5/3+7/3*99/4*2998+10*568/14)
        if chengshu:
            ret = chengshu.group()  # 2*5
            resut = cout(ret)  # 得到乘除法的计算结果 10.0
            # 将2*5替换成10.0
            res = res.replace(ret, resut)  # (9-10.0/3+7/3*99/4*2998+10*568/14)
        else:break
    print(res)  # (9-3.3333333333333335+173134.50000000003+405.7142857142857)
    # 表达式的符号管理把++变成+,--变成-,+-变成-,-+变成-
    res1 = format_exp(res) # 将替换后的结果从新赋值给res
    # 将括号内的加减法都匹配出来
    res_lis = re.findall('[-+]?\d+(?:\.\d+)?',res1)
    print(res_lis)  # ['9', '-3.3333333333333335', '+173134.50000000003', '+405.7142857142857']
    sum_n = 0
    for i in res_lis:
        sum_n += float(i)
    return sum_n
def remove_bracket(express):
    while True:

Extract the innermost parenthesis of an expression

        exp = re.search('\([^()]+\)',express)
        if exp:
            res = exp.group()  # (9-2*5/3+7/3*99/4*2998+10*568/14)
            rep = cal_no(res)  # 173545.88095238098
            print(rep)
            express = express.replace(res,str(rep)) # 因为rep的结果是一个数字
            print(express) # 1-2*((60-30+173545.88095238098*(-40/5))-(-4*3)/(16-3*2))
        else:break
    return express  # 括号内的表达式全部计算完成1-2*-1388338.2476190478
ret = remove_bracket(express)
print(cal_no(re

8. Verify file consistency

# import os
# import hashlib
# def file_md5(path):
#     filesize = os.path.getsize(path)
#     md5 = hashlib.md5()
#     with open(path,'rb') as f:
#         while filesize >= 4096:
#             content = f.read(4096)
#             md5.update(content)
#             filesize -= 4096
#         else:
#             content = f.read(filesize)
#             if content:
#                 md5.update(content)
#     return md5.hexdigest()
#
# def cmp_file(path1,path2):
#     return file_md5(path1) == file_md5(path2)
# path1 = r'D:\s20\day18\视频\4.面向对象整理.mp4'
# path2 = r'D:\s20\day18\视频\tmp.mp4'
# ret = cmp_file(path1,path2)
# print(ret)

9. Print the multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print("%s*%s=%s"%(i,j,i*j),end=' ')
    print()


for i in range(1,10):
    for j in range(i,10):
        print("%s*%s=%s"%(i,j,i*j),end=' ')
    print()

10. Shopping cart operation

Create a txt file named 'Purchase Bill'

goods = []
money = input('请充值充值金额').strip()
with open('商品信息',encoding='utf-8')as f:
    for i in f:
       xinxi = i.strip().split(' ')
       if xinxi[0] == 'name':
           continue
       else:
           dic = dict([('name',xinxi[0]),('price',xinxi[1])])
           goods.append(dic)
print(goods)
"""
页面显示 序号 + 商品名称 + 商品价格
"""
a = 1
for v in goods:
    print(a,v['name'],v['price'])
    a += 1
print('n 购物车结算')
print('q 或 Q 退出')
shop_dic = {
    
    }
sum = 0
a = 1
dic = {
    
    }
balance = 0
while 1:
    shuru = input('请输入序号').strip()
    if shuru.isdigit() and (0 < int(shuru) <= len(goods)):
        print(goods[int(shuru)-1]['name'],goods[int(shuru)-1]['price'])

Add product name, price and quantity to shopping cart

        shop_dic.setdefault(goods[int(shuru)-1]['name'],{
    
    'price':goods[int(shuru)-1]['price'],'amount':0})

Increase product quantity

        shop_dic[goods[int(shuru)-1]['name']]['amount'] += 1
    elif shuru == 'n':
        for k,j in shop_dic.items():
            # python学习交流群:309488165
            # 展示购物车商品名称价格数量
            print(a,k,j['price'],j['amount'])

Dictionary with serial numbers and product names

            dic[a] = k
            a += 1
            sum += int(j['price'])*int(j['amount'])
        if int(money) >= sum:
            print('结算成功')
            balance = int(money)-sum
            for s, b in shop_dic.items():
                print(s, b['price'], b['amount'])
            print('共计消费{}元,剩余金额{}元'.format(sum, balance))
            break
        while int(money) < sum:
            print('余额不足')
            shanchu = input('请输入要删除的商品序号')

If the user chooses to delete the item in the shopping cart, the quantity in the shopping cart will be reduced by one.

            shop_dic[dic[int(shanchu)]]['amount'] -= 1
            sum = sum - int(shop_dic[dic[int(shanchu)]]['price'])
        else:
            print('结算成功')
            balance = int(money) - sum
            for s, b in shop_dic.items():
                print(s, b['price'], b['amount'])
            print('共计消费{}元,剩余金额{}元'.format(sum, balance))
            break
    elif shuru.upper() == 'Q':
            print('程序退出')
            break
    else:
        print('输入有误请重新输入')
with open('购买账单',encoding='utf-8',mode='w') as f1:
    for s, b in shop_dic.items():
        f1.write('商品名称:{} '.format(s))
        f1.write('单价:{} '.format(b['price']))
        f1.write('数量:{}\n'.format(str(b['amount'])))
    f1.write('共计消费{}元\n'.format(sum))
    f1.write('剩余金额%s元'%(balance))

11. Blog Park Login

Create a log and register file

import time
dic = {
    
    
    1: '请登录',
    2: '请注册',
    3: '文章页面',
    4: '日记页面',
    5: '评论页面',
    6: '收藏页面',
    7: '退出程序',
}
def Home_display():
    """

Home page display

    :return:
    """
    print('欢迎来到博客园首页!!!')
    for i in dic:
        print(i,dic[i])
Home_display()
def ster():
    """

User registration function writes username and password to file

    :return:
    """
    user_name = input('请填写注册名称').strip()
    pass_word = input('请填写注册密码').strip()
    with open('register','a+',encoding='utf-8') as f1:
        f1.write('{},{}'.format(user_name,pass_word)+'\n')
        print('注册成功,请登录!!!')

def login_system():
    """

Login function

    :return:
    """
    user_name = []
    time = 3
    with open('register', 'r+', encoding='utf-8') as f:
        for i in f:
            user_name.append(i.strip())
        while time >= 1:
            name = input('请输入用户名')
            wd = input('请输入密码')
            l = name + ',' + wd
            if l in user_name:
                print('登录成功')
                chioce(name)
            else:
                time -= 1
                if time == 0:
                    print('登录次数超出限制,请您注册后登录!')
                    break
                print('用户名或密码错误,剩余{}次机会'.format(time))

def eixt_procedure():
    """

exit the program

    :return:
    """
    print('程序退出,欢迎下次光临')
    exit()

def log(n,func):
    with open('log','a+',encoding='utf-8') as f2:
        current_time = time.strftime("%Y-%m-%d-%X",time.localtime())
        f2.write('{}:{}调用了{}函数'.format(n,current_time,func) + '\n')

def diary(n):
    """

diary page

    :return:
    """
    print('欢迎{}访问日记页面'.format(n))
    log(n, 'diary')
def comment(n):
    """

Comment page

    :return:
    """
    print('欢迎{}访问评论页面'.format(n))
    log(n, 'comment')
def Collection(n):
    """

favorite page

    :return:
    """
    print('欢迎{}访问收藏页面'.format(n))
    log(n, 'Collection')
def Article(n):
    """

Article page

    :return:
    """
    print('欢迎{}访问文章页面'.format(n))
    log(n, 'Article')
lis = [login_system,ster,Article,diary,comment,Collection,eixt_procedure,log]
def chioce(a):
    """

User selection function

    :return:
    """
    while 1:
        number = input('请选择页面:').strip()
        if number.isdigit() and 3 <= int(number) <= 6:
            lis[int(number)-1](a)
        # 不可以输入字母
        elif number.isdigit() and (int(number) ==1 or int(number)==7):
            if int(number)==7:
                eixt_procedure()
            lis[int(number) - 1]()
        else:
            print('请输入正确页面选项:')
def chioce1():
    while 1:
        number = input('请选择登录或注册或退出').strip()
        if number.isdigit() and (1 == int(number) or int(number) == 7 or int(number) == 2) :
            if int(number) == 7:
                eixt_procedure()
            else:
                lis[int(number)-1]()
        else:
            print('输入有误请重新输入')
chioce1()

12. Student course selection system

Create course_file, test.log, vip_admin files

import hashlib
import pickle
import os
import logging

logger = logging.getLogger()

Create a handler for writing to the log file

fh = logging.FileHandler('test.log',encoding='utf-8')

Create another handler for output to the console

# ch = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# ch.setFormatter(formatter)
logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
# logger.addHandler(ch)
logger.setLevel(logging.DEBUG)

# python学习交流群:309488165
# 密码加密
def md5_user(username,password):
    md5 = hashlib.md5(username.encode('utf-8'))
    md5.update(password.encode('utf-8'))
    return md5.hexdigest()

read file

def read_file_name(file_name):
    with open(file_name,'rb') as f:
        while True:
            try:
                res = pickle.load(f)
                if res:
                    yield res
            except EOFError:
                break

write file

def add_file(file_name,content):
    with open(file_name,'ab') as f:
        pickle.dump(content,f)

Create course class

class Course:
    def __init__(self,name,price,period,teacher):
        self.name = name
        self.price = price
        self.period = period
        self.teacher = teacher

    def __str__(self):
        return format('\t课程:' + self.name,'<13') + format('价钱:' + self.price,'<13') + format('周期:' + self.period,'<13') + format('老师:' + self.teacher,'<13')
class Admin:
    msg = [('创建课程', 'course'),
            ('创建学生和学生账号', 'account_num'),
            ('查看所有课程', 'view_courses'),
            ('查看所有学生', 'look_all_student'),
            ('查看所有学生的选课情况', 'look_all_courses'),
            ('退出程序', 'quit')]

Instantiate an administrator

    def __init__(self,username,password,identify='Admin'):
        self.username = username
        self.password = password
        self.identify = identify

Create a course

    def course(self):
        student_name = input('请输入课程名称')
        student_pricce = input('请输入课程价钱')
        student_period = input('请输入课程周期')
        student_teacher = input('请输入授课老师')
        Course1 = Course(student_name,student_pricce,student_period,student_teacher)
        add_file('course_file', Course1)
        return True

Create students and student accounts

    def account_num(self):
        username = input('请输入要创建的姓名')
        password = input('请输入要创建的密码')
        student1 = Student(username,md5_user(username,password))
        add_file('vip_admin', student1)
        return True

View all courses

    def view_courses(self):
        ret = read_file_name('course_file')
        for index,i in enumerate(ret,1):
            print(index,i)   # 因为用__str__所以直接打印对象名直接可以打印他的returnreturn True

View all students

    def look_all_student(self):
        ret = read_file_name('vip_admin')
        for i in ret:
            if i.identify == 'Student':
                print(i.username,i.password)
        return True

View course selection status for all students

    def look_all_courses(self):
        ret = read_file_name('vip_admin')
        for i in ret:
            if i.identify == 'Student':
                print(i.username)
                for j in i.course:
                    print(j)
        return True

exit the program

    def quit(self):
        print('程序退出')
        logger.info(self.username + '——' + self.msg[-1][0])
        exit()

Instantiate an administrator with alex password 123

# alex = Admin('alex',md5_user('alex','123'))
# def write_file_name():
#     with open('vip_admin','wb') as f:
#         pickle.dump(alex,f)
# write_file_name()
class Student:
    msg = [('查看所有课程', 'look_all_course'),
            ('选择课程', 'choice_course'),
            ('查看所选课程', 'look_choice_course'),
            ('退出程序', 'quit')]
    def __init__(self,username,password,identify = 'Student'):
        self.username = username
        self.password = password
        self.identify = identify
        self.course = []

    def look_all_course(self):
        ret = read_file_name('course_file')
        for index, i in enumerate(ret, 1):
            print(index, i)
        return True
    def choice_course(self):
        ret = list(read_file_name('course_file'))
        # print(ret)
        for index, i in enumerate(ret, 1):
            print(index, i)
        while True:
            choice = input('请选择课程>>>:').strip()
            if choice.isdigit() and int(choice) in range(1,len(ret) +1 ):
                print(ret[int(choice)-1].name)
                print([i.name for i in self.course])
                if ret[int(choice)-1].name not in [i.name for i in self.course]:
                    self.course.append(ret[int(choice)-1])
                    with open('vip_admin','rb') as f1,open('vip_admin2','wb') as f2:
                        while True:
                            try:
                                res1 = pickle.load(f1)
                                if res1.username == self.username:
                                    res1.course.append(ret[int(choice)-1])
                                    pickle.dump(res1,f2)
                                else:
                                    pickle.dump(res1, f2)
                            except EOFError:break
                    os.remove('vip_admin')
                    os.rename('vip_admin2','vip_admin')
                    logger.info(self.username + '——' + self.msg[1][0]+ str(ret[int(choice)-1])) # ?????
                    break
                else:
                    print('该课程您已选择')
                    break
            else:
                print('输入有误重新输入')
    def look_choice_course(self):
        ret = read_file_name('vip_admin')
        for i in ret:
            if i.username == self.username:
                for j in i.course:
                    print(j)
        return True
    def quit(self):
        logger.info(self.username + '——' + self.msg[-1][0])
        exit()

Login authentication

def login(username,password):
    ret = read_file_name('vip_admin')
    for i in ret:
        # print(i.username)
        if i.username == username and i.password == md5_user(username,password):
            return i

    else:return False

def auth():
    lis = ['登录','退出']
    while True:
        for index,opt in enumerate(lis,1):
            print(index,opt)
        num = input('请输入你要操作的内容')
        if num.isdigit() and int(num) in range(1,len(lis)+1):
            if num == '1':
                username = input('请输入用户名')
                password = input('请输入密码')
                ret = login(username,password)
                if ret:
                    print('登录成功')
                    logger.info(username + '——' + '登录成功')
                    return ret
                else:
                    print('登录失败')
            elif num == '2':
                exit()
        else:
            print('您输入的序号有误请重新输入')

main function

def main():
    ret = auth()
    # if hasattr(sys.modules[__name__],ret['identify']):
    #     cls = getattr(sys.modules[__name__],ret['identify']) # ???????
    #     # print(sys.modules[__name__]) # <module '__main__' from 'D:/PycharmProjects/s20/大作业/Thursday/学生选课系统升级版/选课系统升级版.py'>
    #     obj = cls(ret['username'],ret['password'])
    if ret:
        # print(ret)
        obj = ret
        # print(obj)
        while True:
            for index,i in  enumerate(obj.msg,1):
                print(index,i[0])
            choice = input('请选择序号')
            if choice.isdigit() and int(choice) in range(1,len(obj.msg) + 1):
                if hasattr(obj,obj.msg[int(choice) - 1][1]):
                    if callable(getattr(obj,obj.msg[int(choice) - 1][1])):
                        ret = getattr(obj, obj.msg[int(choice) - 1][1])()
                        if ret:
                            logger.info(obj.username+'——'+obj.msg[int(choice) - 1][0])
            else:
                print('您输入的序号有误,请重新输入')
main()

at last

Everyone can study the twelve programming questions provided in the article on their own. If you don’t understand something, you can click on the business card at the end of the article to communicate and learn.

Friends who have just started learning python, or those who are interested in python but have not yet started learning, can also click on the business card to receive a large number of learning materials and source code of some cases.

I hope we can learn and make progress together~

Guess you like

Origin blog.csdn.net/aliYz/article/details/132474774