Tianhao Cui

It is about code, it is not about code

  • Home
  • Code
  • Apple
  • Others
All Blogs My Verse

Tianhao Cui

It is about code, it is not about code

  • Home
  • Code
  • Apple
  • Others

Day2-Python-Basics

2020-05-21

Python之路(2)

还是Python基础篇,还是基于上篇文章提到的教程。链接在下

The link of tutorials: Python

在这几天自己写的练习来看,列表和字典是我最容易想到的。这并不代表者其他的方法不好用,毕竟对一个要求每个人都有自己写代码的爱好和习惯。

列表代码练习

购物车小程序

要求:

  • 启动程序后,用户输入工资,打印商品列表
  • 允许用户根据商品编号购买物品
  • 选择物品后,检测余额是否足够购买所选商品
  • 退出时,打印已购买商品和余额
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
35
36
37
38
39
#购物车程序
import sys

product_id=[0,1,2]
#print(type(product_id[0]))
product_list=["Nike","Adidas","Jordan"]
product_price=[200,100,300]
purchased_item=[]
total=0

salary=int(input("Please enter your salary:$"))
c=input("Want to shop?(y/n)")
while(c=="y"):
print("Shopping list")
for i in range(len(product_list)):
print(product_id[i],product_list[i],product_price[i],sep=' ')
p=int(input("Please enter the item ID to purchase."))
#print(type(p))
if(p in product_id):
if salary>=product_price[p]:
print("success!")
print("your new balance is ",salary-product_price[p])
purchased_item.append(product_list[p])
total=total+product_price[p]
salary=salary-product_price[p]
c=input("still want to shop?(y/n)")
else:
print("the item is not affordable!")
c=input("still want to shop?(y/n)")
else:
print("item not available!")
c=input("still want to shop?(y/n)")

print("Your receipt")
for i in range(len(purchased_item)):
print(i,purchased_item[i],sep=' ')
print("your total is:$",total)
sys.exit()

上面的程序应用到了创建列表,列表的操作,逻辑的应用,参数形式的转换,参数间的运算。这样的小程序练习起来十分爽快,程序即没那么复杂,也起到了巩固知识,应用新知识的作用。

文件操作

文件的打开,读取和修改

无论哪一种编程语言,对于文件的操作都是重要的,也是对于代码可自动化的一种基本体现。

用Python实现shell sed的替代功能

SED command in UNIX is stands for stream editor and it can perform lot’s of function on file like,searching,find,replace and so on.

Code

原文本内容

1
1.I enjoy using Windows

实现修改

1
2
3
4
5
6
f=open('test.txt','r')
a=f.readlines()
f=open('test.txt','w')
for i in a:
f.write(i.replace('Windows','MacOS'))
f.close()

修改后文本内容

1
1.I enjoy using MacOS
  • Code
  • Python

扫一扫,分享到微信

微信分享二维码
Day3-Python-Functions
Why MacOS?
© 2021 Tianhao Cui
Hexo Theme Yilia by Litten
  • All Blogs
  • My Verse

tag:

  • Code
  • Blockchain
  • Python
  • Others
  • Interview
  • Apple
  • MacOS
  • Algorithm
  • iPhone

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

And now these three remain:faith,hope,love
But the greatest of these is love