Python基础,day2
程序练习
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
- menu = [['Iphone',4288],['Mac pro',1200],['Book',80]]
- buy_menu = []
- salay = input("Pls input your salay:")
- if salay.isdigit():
- salay = int(salay)
- while True:
- for index,item in enumerate(menu):
- #print(menu.index(item),item)
- print(index,item)
- user_choice = input("Pls input your choose:")
- if user_choice.isdigit():
- user_choice = int(user_choice)
- if user_choice < len(menu) and user_choice >= 0:
- p_list = menu[user_choice]
- if p_list[1] <= salay:
- buy_menu.append(p_list)
- print("Added %s to the shopping list" % (p_list))
- salay -= p_list[1]
- print("The balance is %s" % (salay))
- else:
- print("Your money is no enough,the balance is %s" % (salay))
- print("Your shopping list is",buy_menu)
- exit()
- else:
- print("Sorry,the number of %s is not in the meun list." % (user_choice))
- else:
- print("Pls input the correct number:")
- status = input("Do you want choose another[c/q]:")
- if status == "q":
- print("Your list of buy is", buy_menu)
- print("Your balance is", salay)
- exit(0)
- else:
- print("Pls input the number of your salay.")
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 可返回上一级
- 可随时退出程序
- menu = {
- "jiangxi": {
- "nanchang": {
- "xinjianxian": ["ncu", "bank"],
- "nanchangxian": ["caijingdaxue", "jishuxueyuan"]
- },
- "jiujiang": {
- "xiushuixian": "修水县地图",
- "jiujiangxian": "九江县地图"
- }
- },
- "guangdong": {
- "shenzhen": {
- "longhuaqu": "龙华区地图",
- "luohuqu": "罗湖区地图"
- }
- }
- }
- menu["jiangxi"]["nanchang"]["xinjianxian"][0] += " univercity"
- exit_flag = False
- while not exit_flag:
- for i in menu:
- print(i)
- choice = input("1>>:")
- if choice in menu:
- while not exit_flag:
- for i2 in menu[choice]:
- print("\t", i2)
- choice2 = input("2>>:")
- if choice2 in menu[choice]:
- while not exit_flag:
- for i3 in menu[choice][choice2]:
- print("\t\t", i3)
- choice3 = input("3>>:")
- if choice3 in menu[choice][choice2]:
- for i4 in menu[choice][choice2][choice3]:
- print("\t\t\t",i4)
- choice4 = input("4按b返回上层>>:")
- if choice4 == "b":
- pass
- elif choice4 == "q":
- exit_flag = True
- if choice3 == "b":
- break
- elif choice3 == "q":
- exit_flag = True
- if choice2 == "b":
- break
- elif choice2 == "q":
- exit_flag = True
多级菜单
5. 文件操作
对文件操作流程
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
- 风吹雨成花
- 时间追不上白马
- 你年少掌心的梦话
- 依然紧握着吗
- 云翻涌成夏
- 眼泪被岁月蒸发
- 这条路上的你我她
- 有谁迷路了吗
- 我们说好不分离
- 要一直一直在一起
- 就算与时间为敌
- 就算与全世界背离
- 风吹亮雪花
- 吹白我们的头发
- 当初说一起闯天下
- 你们还记得吗
- 那一年盛夏
- 心愿许的无限大
- 我们手拉手也成舟
- 划过悲伤河流
- 你曾说过不分离
- 要一直一直在一起
- 现在我想问问你
- 是否只是童言无忌
- 天真岁月不忍欺
- 青春荒唐我不负你
- 大雪求你别抹去
- 我们在一起的痕迹
- 大雪也无法抹去
- 我们给彼此的印记
- 今夕何夕
- 青草离离
- 明月夜送君千里
- 等来年 秋风起
打开的music.py文件内容
- #文件句柄
- f = open("music.py","r",encoding="utf-8") #读取文件内容,不可写
- print(f.read()) #读取所有
- print(f.readlines()) #读取所有行,输出成列表
- print(f.readline()) #读取一行
- #low methon
- '''
- for index,line in enumerate(f.readlines()):
- if index == 4:
- print("line pass".center(50,"-"))
- continue
- print(line.strip()) #strip()取消空格和\n换行
- '''
- #higher methon
- '''
- count = 0
- for line in f: #一行一行读取,内存内只保留一行,迭代器
- if count == 4:
- print("line pass".center(50, "-"))
- count += 1
- continue
- print(line.strip())
- count += 1
- '''
- #f = open("music.py","w",encoding="utf-8") #文件存在会覆盖写入,不存在会新建写入,不可读
- #f.write("test write")
- #f = open("music.py","a",encoding="utf-8") #追加不会覆盖原有,但不可读
- #f.write("\ntest append\n")
- #print(f.read(5)) #读取几个字
- #print(f.tell()) #把文件句柄所在的指针指向的位置打印出来,按字符计数
- #f.seek(0) #移动光标,回到某个位置
- ##print(f.seekable()) #是否可以光标移动
- #print(f.read(5))
- #print(f.encoding) #打印文件编码
- #print(f.name) #打印文件名
- #print(f.isatty()) #是否是终端设备,例如:打印机
- #f.flush() #把文件从内存刷新到磁盘中
- #f.close() #关闭文件
- #print(f.closed) #判断文件是否关闭
- #f.truncate(10) #截断,从头开始截取
- #f = open("music.py","r+",encoding="utf-8") #文件句柄,读写,当指针指向为0的时候,替换写在最前面,当指针指向非零的时候,以追加的模式最加到最后
- #f = open("music.py","w+",encoding="utf-8") #文件句柄,写读,很少用
- #f = open("music.py","a+",encoding="utf-8") #文件句柄,追加读写,文件打开指针就跳到结尾,读需要把指针移动到前面位置
- #f = open("music.py","rb") #文件句柄,二进制文件
- #f = open("music.py","wb")
- f = open("music.py","ab")
- f.write("hello world\n".encode())
文件修改
- f = open("music.py","r",encoding="utf-8")
- f_new = open("music_new.py","w",encoding="utf-8")
- for line in f:
- if "我们说好" in line:
- line = line.replace("我们说好","我们一起说好")
- f_new.write(line)
- f.close()
- 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又支持同时对多个文件的上下文进行管理。
- import sys
- find_str = sys.argv[1]
- replace_str = sys.argv[2]
- #with 语句
- with open("music.py","r",encoding="utf-8") as f, \
- open("music_new.py", "w", encoding="utf-8") as f_new:
- for line in f:
- if find_str in line:
- line = line.replace(find_str, replace_str)
- 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
- #-*- coding:utf-8 -*- #声明文件编码格式
- import sys
- print(sys.getdefaultencoding()) #python3 默认编码格式是utf-8
- s = "你好" #unicode格式,Python3里所有的数据类型都是unicode
- s_to_gbk = s.encode("gbk")
- print(s_to_gbk)
- s_to_utf8 = s.encode()
- print(s_to_utf8)
- gbk_to_utf8 = s_to_gbk.decode("gbk").encode("utf-8")
- print(gbk_to_utf8)
- print("分割线".center(50,"-"))
- print(s.encode("utf-8"))
- print(s.encode("gbk"))
- print(s.encode("gb2312"))
- print(s.encode("gb2312").decode("gb2312").encode("utf-8").decode("utf-8").encode("gbk"))
程序练习
程序1: 实现简单的shell sed替换功能
- sed_before = input("Pls input the old word that you want sed:")
- sed_after = input("Pls input the new word that you want sed:")
- count = 0
- f = open("music.py","r",encoding="utf -8")
- f_sed = open("music_sed.py","w",encoding="utf-8")
- for line in f:
- if sed_before in line:
- line = line.replace(sed_before,sed_after)
- count += 1
- f_sed.write(line)
- if count == 0:
- print("The old word is not in the file,pls config")
- f.close()
- f_sed.close()
方法一
- sed_before = input("Pls input the old word that you want sed:")
- sed_after = input("Pls input the new word that you want sed:")
- count = 0
- with open("music.py","r",encoding="utf -8") as f,\
- open("music_sed.py","w",encoding="utf-8") as f_sed:
- for line in f:
- if sed_before in line:
- line = line.replace(sed_before, sed_after)
- count += 1
- f_sed.write(line)
- if count == 0:
- print("The old word is not in the file,pls config")
方法二:with语句优化版
程序2:修改haproxy配置文件
Python基础,day2的更多相关文章
- Python基础-day2
1.Python模块python 中导入模块使用import语法格式:import module_name示例1: 导入os模块system('dir')列出当前目录下的所有文件 # _*_ codi ...
- python基础day2
一.python字符串 字符串是 Python 中最常用的数据类型.可以使用引号('或")来创建字符串 1.1Python访问字符串中的值 Python不支持单字符类型,单字符在 Pytho ...
- python基础day2作业:购物车
#功能:1.可注册账号2.登录买家账号3.可查询编辑购物车里商品4.可以余额充值5.可提示余额不足6.购物车结算 #使用:1.第一次使用先注册账号填写账号金额2.账号金额信息保存在buyer_acco ...
- Day2 - Python基础2 列表、字典、集合
Python之路,Day2 - Python基础2 本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一, ...
- Python基础学习总结(持续更新)
https://www.cnblogs.com/jin-xin/articles/7459977.html 嗯,学完一天,白天上班,眼睛要瞎了= = DAY1 1,计算机基础. CPU:相当于人的大脑 ...
- Python基础 小白[7天]入门笔记
笔记来源 Day-1 基础知识(注释.输入.输出.循环.数据类型.随机数) #-*- codeing = utf-8 -*- #@Time : 2020/7/11 11:38 #@Author : H ...
- python之最强王者(2)——python基础语法
背景介绍:由于本人一直做java开发,也是从txt开始写hello,world,使用javac命令编译,一直到使用myeclipse,其中的道理和辛酸都懂(请容许我擦干眼角的泪水),所以对于pytho ...
- Python开发【第二篇】:Python基础知识
Python基础知识 一.初识基本数据类型 类型: int(整型) 在32位机器上,整数的位数为32位,取值范围为-2**31-2**31-1,即-2147483648-2147483647 在64位 ...
- Python小白的发展之路之Python基础(一)
Python基础部分1: 1.Python简介 2.Python 2 or 3,两者的主要区别 3.Python解释器 4.安装Python 5.第一个Python程序 Hello World 6.P ...
- Python之路3【第一篇】Python基础
本节内容 Python简介 Python安装 第一个Python程序 编程语言的分类 Python简介 1.Python的由来 python的创始人为吉多·范罗苏姆(Guido van Rossum) ...
随机推荐
- Qt5官方demo解析集35——Music Player(使用winextras模块)
本系列所有文章可以在这里查看http://blog.csdn.net/cloud_castle/article/category/2123873 接上文Qt5官方demo解析集34——Concentr ...
- UML该元素的行为为基础的元素
Behavioral thingsare the dynamic parts of UML models. These are the verbs of a model, representin ...
- ZOJ 2319 Beatuiful People(单调递增序列的变形)
Beautiful People Time Limit: 5 Seconds Memory Limit: 32768 KB Special Judge The most prest ...
- 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 ...
- wpf 触摸屏 button 背景为null的 问题
原文:wpf 触摸屏 button 背景为null的 问题 <!-- button样式--> <Style x:Key="myBtn" TargetType=&q ...
- SAP HR工资配置项1---工资计算周期配置
对于工资计算,三个方面需要配置:工资计算期.工资类型.工资. 下面是工资期内的配置: 1.在定义参数 在参数指示工资的频率. 主题 设置期间參数 菜单路径 SAP 用户化实施指南→工资核算→工资核算: ...
- linq to entity DistinctBy && DefaultIfEmpty
根据某属性去重 使用第三方库: https://github.com/morelinq/MoreLINQ Install-Package morelinq -Version 3.0.0 data.Di ...
- AngularJS 计时器
<div ng-controller="MyController"> <!--显示$scope.clock的now属性--> <h1>hello ...
- ASP .NET Controller返回类型
返回类型 return View(model); 即返回htmlreturn Json("String"); 返回Json格式的数据return File(new byte[] { ...
- VC中出现“烫”和“屯”的原因(栈区的每一个字节都被0xCC填充了,也就是int 3h的机器码,动态分配的堆,VC的Debug用0xCD填充堆的空间,就出现了“屯”)
相信经常用VC的朋友对屏幕输出的一大堆“烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫”不会陌生,但是也许会很奇怪,为什么会出现“烫”字呢?莫非改程序导致系统运行缓慢,发热过高???非也!下面让我解释 ...