程序练习

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额
  1. menu = [['Iphone',4288],['Mac pro',1200],['Book',80]]
  2. buy_menu = []
  3. salay = input("Pls input your salay:")
  4. if salay.isdigit():
  5. salay = int(salay)
  6. while True:
  7. for index,item in enumerate(menu):
  8. #print(menu.index(item),item)
  9. print(index,item)
  10. user_choice = input("Pls input your choose:")
  11. if user_choice.isdigit():
  12. user_choice = int(user_choice)
  13. if user_choice < len(menu) and user_choice >= 0:
  14. p_list = menu[user_choice]
  15. if p_list[1] <= salay:
  16. buy_menu.append(p_list)
  17. print("Added %s to the shopping list" % (p_list))
  18. salay -= p_list[1]
  19. print("The balance is %s" % (salay))
  20. else:
  21. print("Your money is no enough,the balance is %s" % (salay))
  22. print("Your shopping list is",buy_menu)
  23. exit()
  24. else:
  25. print("Sorry,the number of %s is not in the meun list." % (user_choice))
  26. else:
  27. print("Pls input the correct number:")
  28. status = input("Do you want choose another[c/q]:")
  29. if status == "q":
  30. print("Your list of buy is", buy_menu)
  31. print("Your balance is", salay)
  32. exit(0)
  33. else:
  34. print("Pls input the number of your salay.")

程序: 三级菜单

要求:

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序
  1. menu = {
  2. "jiangxi": {
  3. "nanchang": {
  4. "xinjianxian": ["ncu", "bank"],
  5. "nanchangxian": ["caijingdaxue", "jishuxueyuan"]
  6. },
  7. "jiujiang": {
  8. "xiushuixian": "修水县地图",
  9. "jiujiangxian": "九江县地图"
  10. }
  11. },
  12. "guangdong": {
  13. "shenzhen": {
  14. "longhuaqu": "龙华区地图",
  15. "luohuqu": "罗湖区地图"
  16. }
  17. }
  18. }
  19. menu["jiangxi"]["nanchang"]["xinjianxian"][0] += " univercity"
  20.  
  21. exit_flag = False
  22. while not exit_flag:
  23. for i in menu:
  24. print(i)
  25. choice = input("1>>:")
  26. if choice in menu:
  27. while not exit_flag:
  28. for i2 in menu[choice]:
  29. print("\t", i2)
  30. choice2 = input("2>>:")
  31. if choice2 in menu[choice]:
  32. while not exit_flag:
  33. for i3 in menu[choice][choice2]:
  34. print("\t\t", i3)
  35. choice3 = input("3>>:")
  36. if choice3 in menu[choice][choice2]:
  37. for i4 in menu[choice][choice2][choice3]:
  38. print("\t\t\t",i4)
  39. choice4 = input("4按b返回上层>>:")
  40. if choice4 == "b":
  41. pass
  42. elif choice4 == "q":
  43. exit_flag = True
  44. if choice3 == "b":
  45. break
  46. elif choice3 == "q":
  47. exit_flag = True
  48. if choice2 == "b":
  49. break
  50. elif choice2 == "q":
  51. exit_flag = True

多级菜单

5. 文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
  1. 风吹雨成花
  2. 时间追不上白马
  3. 你年少掌心的梦话
  4. 依然紧握着吗
  5. 云翻涌成夏
  6. 眼泪被岁月蒸发
  7. 这条路上的你我她
  8. 有谁迷路了吗
  9. 我们说好不分离
  10. 要一直一直在一起
  11. 就算与时间为敌
  12. 就算与全世界背离
  13. 风吹亮雪花
  14. 吹白我们的头发
  15. 当初说一起闯天下
  16. 你们还记得吗
  17. 那一年盛夏
  18. 心愿许的无限大
  19. 我们手拉手也成舟
  20. 划过悲伤河流
  21. 你曾说过不分离
  22. 要一直一直在一起
  23. 现在我想问问你
  24. 是否只是童言无忌
  25. 天真岁月不忍欺
  26. 青春荒唐我不负你
  27. 大雪求你别抹去
  28. 我们在一起的痕迹
  29. 大雪也无法抹去
  30. 我们给彼此的印记
  31. 今夕何夕
  32. 青草离离
  33. 明月夜送君千里
  34. 等来年 秋风起

打开的music.py文件内容

  1. #文件句柄
  2. f = open("music.py","r",encoding="utf-8") #读取文件内容,不可写
  3. print(f.read()) #读取所有
  4. print(f.readlines()) #读取所有行,输出成列表
  5. print(f.readline()) #读取一行
  6.  
  7. #low methon
  8. '''
  9. for index,line in enumerate(f.readlines()):
  10. if index == 4:
  11. print("line pass".center(50,"-"))
  12. continue
  13. print(line.strip()) #strip()取消空格和\n换行
  14. '''
  15. #higher methon
  16. '''
  17. count = 0
  18. for line in f: #一行一行读取,内存内只保留一行,迭代器
  19. if count == 4:
  20. print("line pass".center(50, "-"))
  21. count += 1
  22. continue
  23. print(line.strip())
  24. count += 1
  25. '''
  26.  
  27. #f = open("music.py","w",encoding="utf-8") #文件存在会覆盖写入,不存在会新建写入,不可读
  28. #f.write("test write")
  29.  
  30. #f = open("music.py","a",encoding="utf-8") #追加不会覆盖原有,但不可读
  31. #f.write("\ntest append\n")
  32.  
  33. #print(f.read(5)) #读取几个字
  34. #print(f.tell()) #把文件句柄所在的指针指向的位置打印出来,按字符计数
  35. #f.seek(0) #移动光标,回到某个位置
  36. ##print(f.seekable()) #是否可以光标移动
  37. #print(f.read(5))
  38. #print(f.encoding) #打印文件编码
  39. #print(f.name) #打印文件名
  40. #print(f.isatty()) #是否是终端设备,例如:打印机
  41. #f.flush() #把文件从内存刷新到磁盘中
  42. #f.close() #关闭文件
  43. #print(f.closed) #判断文件是否关闭
  44. #f.truncate(10) #截断,从头开始截取
  45.  
  46. #f = open("music.py","r+",encoding="utf-8") #文件句柄,读写,当指针指向为0的时候,替换写在最前面,当指针指向非零的时候,以追加的模式最加到最后
  47. #f = open("music.py","w+",encoding="utf-8") #文件句柄,写读,很少用
  48. #f = open("music.py","a+",encoding="utf-8") #文件句柄,追加读写,文件打开指针就跳到结尾,读需要把指针移动到前面位置
  49. #f = open("music.py","rb") #文件句柄,二进制文件
  50. #f = open("music.py","wb")
  51. f = open("music.py","ab")
  52. f.write("hello world\n".encode())

文件修改

  1. f = open("music.py","r",encoding="utf-8")
  2. f_new = open("music_new.py","w",encoding="utf-8")
  3. for line in f:
  4. if "我们说好" in line:
  5. line = line.replace("我们说好","我们一起说好")
  6. f_new.write(line)
  7. f.close()
  8. f_new.close()

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理。

  1. import sys
  2. find_str = sys.argv[1]
  3. replace_str = sys.argv[2]
  4.  
  5. #with 语句
  6. with open("music.py","r",encoding="utf-8") as f, \
  7. open("music_new.py", "w", encoding="utf-8") as f_new:
  8. for line in f:
  9. if find_str in line:
  10. line = line.replace(find_str, replace_str)
  11. f_new.write(line)

6. 字符编码与转码

说明:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

  1. #-*- coding:utf-8 -*- #声明文件编码格式
  2. import sys
  3. print(sys.getdefaultencoding()) #python3 默认编码格式是utf-8
  4. s = "你好" #unicode格式,Python3里所有的数据类型都是unicode
  5. s_to_gbk = s.encode("gbk")
  6. print(s_to_gbk)
  7. s_to_utf8 = s.encode()
  8. print(s_to_utf8)
  9.  
  10. gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8")
  11. print(gbk_to_utf8)
  12.  
  13. print("分割线".center(50,"-"))
  14. print(s.encode("utf-8"))
  15. print(s.encode("gbk"))
  16. print(s.encode("gb2312"))
  17. print(s.encode("gb2312").decode("gb2312").encode("utf-8").decode("utf-8").encode("gbk"))

程序练习  

程序1: 实现简单的shell sed替换功能

  1. sed_before = input("Pls input the old word that you want sed:")
  2. sed_after = input("Pls input the new word that you want sed:")
  3. count = 0
  4. f = open("music.py","r",encoding="utf -8")
  5. f_sed = open("music_sed.py","w",encoding="utf-8")
  6. for line in f:
  7. if sed_before in line:
  8. line = line.replace(sed_before,sed_after)
  9. count += 1
  10. f_sed.write(line)
  11. if count == 0:
  12. print("The old word is not in the file,pls config")
  13. f.close()
  14. f_sed.close()

方法一

  1. sed_before = input("Pls input the old word that you want sed:")
  2. sed_after = input("Pls input the new word that you want sed:")
  3. count = 0
  4. with open("music.py","r",encoding="utf -8") as f,\
  5. open("music_sed.py","w",encoding="utf-8") as f_sed:
  6. for line in f:
  7. if sed_before in line:
  8. line = line.replace(sed_before, sed_after)
  9. count += 1
  10. f_sed.write(line)
  11. if count == 0:
  12. print("The old word is not in the file,pls config")

方法二:with语句优化版

程序2:修改haproxy配置文件

Python基础,day2的更多相关文章

  1. Python基础-day2

    1.Python模块python 中导入模块使用import语法格式:import module_name示例1: 导入os模块system('dir')列出当前目录下的所有文件 # _*_ codi ...

  2. python基础day2

    一.python字符串 字符串是 Python 中最常用的数据类型.可以使用引号('或")来创建字符串 1.1Python访问字符串中的值 Python不支持单字符类型,单字符在 Pytho ...

  3. python基础day2作业:购物车

    #功能:1.可注册账号2.登录买家账号3.可查询编辑购物车里商品4.可以余额充值5.可提示余额不足6.购物车结算 #使用:1.第一次使用先注册账号填写账号金额2.账号金额信息保存在buyer_acco ...

  4. Day2 - Python基础2 列表、字典、集合

    Python之路,Day2 - Python基础2   本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一, ...

  5. Python基础学习总结(持续更新)

    https://www.cnblogs.com/jin-xin/articles/7459977.html 嗯,学完一天,白天上班,眼睛要瞎了= = DAY1 1,计算机基础. CPU:相当于人的大脑 ...

  6. Python基础 小白[7天]入门笔记

    笔记来源 Day-1 基础知识(注释.输入.输出.循环.数据类型.随机数) #-*- codeing = utf-8 -*- #@Time : 2020/7/11 11:38 #@Author : H ...

  7. python之最强王者(2)——python基础语法

    背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...

  8. Python开发【第二篇】:Python基础知识

    Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...

  9. Python小白的发展之路之Python基础(一)

    Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...

  10. Python之路3【第一篇】Python基础

    本节内容 Python简介 Python安装 第一个Python程序 编程语言的分类 Python简介 1.Python的由来 python的创始人为吉多·范罗苏姆(Guido van Rossum) ...

随机推荐

  1. Qt5官方demo解析集35——Music Player(使用winextras模块)

    本系列所有文章可以在这里查看http://blog.csdn.net/cloud_castle/article/category/2123873 接上文Qt5官方demo解析集34——Concentr ...

  2. UML该元素的行为为基础的元素

     Behavioral thingsare the dynamic parts of UML models. These are the verbs of a model, representin ...

  3. ZOJ 2319 Beatuiful People(单调递增序列的变形)

    Beautiful People Time Limit: 5 Seconds      Memory Limit: 32768 KB      Special Judge The most prest ...

  4. ATS项目更新(3) 远程同步到执行机器

    1: echo %time% 2: 3: 4: rem ** ipc and mapping 5: c: 6: net use x: /del 7: net use y: /del 8: net us ...

  5. wpf 触摸屏 button 背景为null的 问题

    原文:wpf 触摸屏 button 背景为null的 问题 <!-- button样式--> <Style x:Key="myBtn" TargetType=&q ...

  6. SAP HR工资配置项1---工资计算周期配置

    对于工资计算,三个方面需要配置:工资计算期.工资类型.工资. 下面是工资期内的配置: 1.在定义参数 在参数指示工资的频率. 主题 设置期间參数 菜单路径 SAP 用户化实施指南→工资核算→工资核算: ...

  7. linq to entity DistinctBy && DefaultIfEmpty

    根据某属性去重 使用第三方库: https://github.com/morelinq/MoreLINQ Install-Package morelinq -Version 3.0.0 data.Di ...

  8. AngularJS 计时器

    <div ng-controller="MyController"> <!--显示$scope.clock的now属性--> <h1>hello ...

  9. ASP .NET Controller返回类型

    返回类型 return View(model); 即返回htmlreturn Json("String"); 返回Json格式的数据return File(new byte[] { ...

  10. VC中出现“烫”和“屯”的原因(栈区的每一个字节都被0xCC填充了,也就是int 3h的机器码,动态分配的堆,VC的Debug用0xCD填充堆的空间,就出现了“屯”)

    相信经常用VC的朋友对屏幕输出的一大堆“烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫”不会陌生,但是也许会很奇怪,为什么会出现“烫”字呢?莫非改程序导致系统运行缓慢,发热过高???非也!下面让我解释 ...