程序练习

程序:购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
  4. 可随时退出,退出时,打印已购买商品和余额
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.")

程序: 三级菜单

要求:

  1. 打印省、市、县三级菜单
  2. 可返回上一级
  3. 可随时退出程序
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. 文件操作

对文件操作流程

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

打开的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的更多相关文章

  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. Java -Android 得知(第四天)

    添加一个新的Activity    我们已经了解到一个Activity就相当于是一个界面(当然了.这样说并不严格,但易于理解). 当我们创建一个安卓应用程序之后.就默认创建了: ①.一个继承Activ ...

  2. 分位数(quantiles)、Z-score 与 F-score

    0. 分位数(quantiles) 因为累计分布函数(cdf,F−1)是单调增函数,因此其有反函数,不妨记为 F−1. 其真实的含义在于,如果 F 是 X 的 cdf,则 F−1(α) 的函数值为: ...

  3. 新浪微博Python客户端接口OAuth2

    Keyword: Python Oauth2 微博 sina weibo #!/usr/bin/env python # -*- coding: utf-8 -*- __version__ = '1. ...

  4. .net reactor 学习系列(三)---.net reactor代码自动操作相关保护功能

    原文:.net reactor 学习系列(三)---.net reactor代码自动操作相关保护功能         接上篇,上篇已经学习了界面的各种功能以及各种配置,这篇准备学习下代码控制许可证. ...

  5. 谷歌推出备份新工具:Google Drive将同步计算机文件

    Google 正在将云端硬盘 Drive 转变成更强大的文件备份工具.很快,Google Drive 将能监测并备份你电脑上的(几乎)所有文件,只要是你勾选的文档,Drive 就能同步至云端. 具体来 ...

  6. ubuntu 关闭 phpmyadmin

    apache 有很多管理服务器的命令.apt-get installl phpmyadmin后突然想暂时关闭phpmyadmin,只需要a2disconf phpmyadmin即可.需要启用的时候再输 ...

  7. js的位置和执行情况

    放到<head>中的<script>在body加载之前就已经运行了. 写在body中的<script>是随着页面的加载而一个个执行的.

  8. 用MVVM模式开发中遇到的零散问题总结(3)——自制正则表达式万能绑定转换器

    原文:用MVVM模式开发中遇到的零散问题总结(3)--自制正则表达式万能绑定转换器 前言 最近接受了3个项目的洗礼,出差近3个月,各种北京.广州.昆明来回奔波,好久没写博客了,之前我觉得我遇到的问题都 ...

  9. MVC 身份验证和异常处理过滤器

    :在Global中注册为全局过滤器,应用于所有的Controller的Action 参数类均继承自ControllerContext,主要包含属性请求上下文.路由数据.结果 using FilterE ...

  10. main()如果返回0,则代表程序正常退出,返回非零代表程序异常退出。

    读到这里,大家应该了解了main函数返回值的来龙去脉了.下面介绍一下main函数返回值的作用以及如何获得这个返回值.main函数的返回值用于说明程序的退出状态.如果返回0,则代表程序正常退出.返回其它 ...