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

Python-Basics-Summary

2020-05-26

Python基础篇(总结)

这一篇文章是对前一段基础学习的遗漏补充和总结。之前的文章写完了Python之路Day1,2,3,这篇文章也会包含Python之路Day4,5。放上链接

The link of tutorials:Day4 Day5

编程语言(Programming languages)

Machine languages –> Assembly languages –> high-level languages

为什么要在提到这个问题呢?我觉得我们应该记住编程语言是如何一步步发展过来的,而我们现在所使用的大多数编程语言都是high-level languages(高级语言)毕竟user-friendly还是很重要,开发效率也更高。而之前提到的高级语言中的编译性和解释型语言在这篇就不多提了。但需要强调的是Python是一门先编译后解释的语言

字符编码(Character encoding)

Python2.X和Python3.X的默认编码是不同的,这也就是为什么我们看到好多代码文件需要在文件开始处注释如何编码。例如:--coding:utf-8 --
1.Python2 ASCII

ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)

2.Python3 Unicode

ASCII码无法将世界上的各种文字和符号全部表示,所以,就需要新出一种可以代表所有字符和符号的编码,即:Unicode

编码与解码(Encoding and decoding)

  • 将字符串已utf-8形式编码
  • 将编码后的字符串再已utf-8形式解码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    s='昊'
    utf8=s.encode('utf-8')
    m=utf8.decode('utf-8')

    print(s)
    print(type(s))
    print(utf8)
    print(type(utf8))
    print(m)
    输出
    1
    2
    3
    4
    5
    昊
    <class 'str'>
    b'\xe6\x98\x8a'
    <class 'bytes'>
    昊
    上面提到的文件编码方式都是Python解释器中的默认编码方式,所以不同语言已unicode加载到内存中,程序就可以正常显示。我们也可以发现字符在已utf-8编码后,字符格式为bytes而不是之前的str

    函数

    内置函数(Built-in functions)

    列举一些常见的内置函数
  1. strip()
  2. open()
  3. len()
  4. range()
  5. isdigit()
  6. enumerate()(索引)
    1
    2
    3
    list=["a","b","c"]
    for count,list in enumerate (list 1):
    print(count,list,sep=' ')
  7. map()(映射)
    1
    2
    3
    4
    5
    6
    list_num=[1,2,3]
    def func(x):
    return x+1
    a=map(func,list_num)
    print(a)
    print(list(a))
  8. lambda()(匿名函数)
    1
    2
    3
    a=lambda x:x+1
    for i in range(3):
    print(a(i))

    装饰器,生成器,和迭代器

    装饰器(Decorator)

    我的理解的装饰器概念是为要执行的函数来提前进行修饰。而修饰可以是为函数增加执行要求。登陆验证是一个很好的例子来学习装饰器。如果用户登陆后不必反复验证用户身份。教程中有对这一部分的详细解释,而我下面用更简单的代码来为装饰器举例。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    #defining a decorator
    n=False
    def decorator(func):
    def inner(*args,**kwargs):
    global n
    if n==False:
    password=input("pwd:")
    if password=='1234':
    print("nice to meet you!")
    n=True
    print(n)
    res = func(*args,**kwargs)
    return res
    if n==True:
    res = func(*args,**kwargs)
    return res
    return inner
    1
    2
    3
    4
    5
    6
    @decorator
    def test():
    print("nice to meet you too!")
    @decorator
    def test2():
    print("good to see you again!")
    1
    2
    3
    4
    #第一次执行程序时,需输入密码来执行后续函数
    test()
    #跳过输入密码步骤,直接执行后续函数
    test2()

输出:

1
2
3
4
5
pwd:1234
nice to meet you!
True
nice to meet you too!
good to see you again!

生成器和迭代器(Generator and Iterator)

迭代器在执行时通过对生成器函数的不断调用来运算出新的对象,直到所有的参数被访问完毕。为了避免无限循环的产生,可以通过raise StopIteration来终止结束迭代。
斐波那契函数(Fibonacci )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def fibonacci(n): #generator
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) #iterator
while True:
try:
print (next(f), end=" ")
except StopIteration:
print("done!")

模块(Modules)

模块分类:

  • 标准库 (顾名思义就是安装Python时程序自带的模块)
  • 开源模块 (网络上共享的开源模块)
  • 自定义(用户自己编写的模块)

我们编写程序时调用其他文件里的代码就是对模块的一种调用。而我们对特定的内置函数使用,有时也必须先调用内置函数相关的模块。 举例:我们在用Python做数据分析时,常常调用numpy,matplotlib,或pandas。或者我们制作区块链时(Blockchain)需要调用哈希算法对数据进行加密处理

1
Import hashlib as hasher
1
2
import pandas as pd
import matplotlib.pyplot as plt

By the way: 区块链也是值得学习和探讨的技术,以后也可以单独写一篇文章来总结以下。

json & pickle

  • json:只可以用于字符串或者字典等与python数据类型之间的序列化与反序列化之间的操作
  • pickle:可以用于python类有类型与python数据类型之间的序列化与反序列化的操作

四个主要功能:dumps,dump,loads,load
json模块的使用例子会在后面练习代码的部分展示出来。

练习代码(Practice code)

简单模拟ATM功能
经验:没有简单的代码,只有不熟悉的代码。写代码方式千奇百怪,总有更优化的代码。我们都在摸索中进步!

遇到的困难既总结(看似小的问题有时会花费好几个小时解决):

  • json文件load和dump时不能处理多个对象
  • json数据更新后,原有数据消失,格式错误。(当我们处理文件数据时,我们会使用read,write和append对目标对象进行加工。ATM程序需要更新数据,而不是添加或者覆盖)解决方法在accounts.py里的dumps_modify()函数。总感觉自己的解决方法有点笨拙,但是没有查到…
  • 函数返回值不更新(调用错误参数)
1
2
3
4
#程序中的代码操作都是基于下面数据格式进行更改,更新和处理的
{"id": "liu", "password": "1222", "balance": 700.0, "credit": "1000", "status": "0"}
{"id": "hao", "password": "808", "balance": 350.0, "credit": "1000", "status": "0"}
{"id": "haha", "password": "1234", "balance": 500.0, "credit": "1000", "status": "0"}

1.main.py

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
#程序入口(Program entrance)
import os
import sys
import atm_admin
import atm_users

def main():
menu={
'1':atm_admin
}
print("Welcome to the ATM system")
print("1---------Admin Accounts")
print("2---------Users Accounts")
print("3---------Exit")
c=input("Your choice>>").strip()
if c == '1':
atm_admin.run_manage()
elif c == '2':
atm_users.run_users()
elif c == '3':
sys.exit()
else:
return main()

if __name__ == '__main__':
main()

2.atm_admin.py

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#管理员界面(Admin Menu)
import os
import sys
import json
import getpass
from accounts import dump_accounts,dump_modify,current_balance,update_dict

def users_login():
print("Please log in")
users_username=input("ID(username):<<")
users_password=getpass.getpass("Password:<<")
user_data=open("accounts.json",'r').readlines()
for line in user_data:
user=json.loads(line)
if user['password']==users_password and user['id']==users_username:
if user['status']=='0':
print("Welcome %s" %users_username)
users_menu(user)
else:
print("Account:%s has been locked,please contact Admin"%user['id'])
sys.exit()
print("Invaild ID or Password!")
return users_login()

def users_menu(user_data):
users_list=["Account info","Withdraw","Deposit","Log out"]
print("*****Users menu******")
for count,users_list in enumerate(users_list,1):
print(count,users_list,sep=' ')
users_choice=input("Please select your choice:>>")
if users_choice=='1':
users_view_account(user_data)
elif users_choice=='2':
users_withdraw(user_data)
elif users_choice=='3':
users_deposit(user_data)
else:
sys.exit()

def users_view_account(v_data):
#print(v_data)
current_balance(update_dict(v_data))
#print("Your balance is:",v_data["balance"])
#print("Your credit line is:",v_data["credit"])
return users_menu(update_dict(v_data))

def users_withdraw(withdraw_data):
print("ID:",withdraw_data['id'])
#print("Your balance is:",withdraw_data['balance'])
current_balance(withdraw_data)
withdraw_amount=float(input("How much do you want:>>"))
old_balance=withdraw_data['balance']
if withdraw_amount<=float(old_balance):
new_balance=float(old_balance)-withdraw_amount
#withdraw_data['balance']=new_balance
dump_modify(withdraw_data,withdraw_data['id'],new_balance)
print("Success!")
#print(withdraw_data)
#print("Your new balance is",withdraw_data['balance'])
else:
print("Invaild input! You do not have enough money in your account")
#return users_withdraw(withdraw_data)
return users_menu(update_dict(withdraw_data))

def users_deposit(deposit_data):
print("ID:",deposit_data['id'])
#print("Your balance is:",deposit_data['balance'])
current_balance(deposit_data)
deposit_amount=float(input("Please enter your deposit:>>"))
old_balance=deposit_data['balance']
new_balance=float(old_balance)+deposit_amount
deposit_data['balance']=new_balance
dump_modify(deposit_data,deposit_data['id'],new_balance)
print("Success")
#print("Your new balance is",deposit_data['balance'])
return users_menu(update_dict(deposit_data))

def run_users():
users_login()

3.atm_users.py

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#普通用户界面(users menu)
import os
import sys
import json
import getpass
from accounts import dump_accounts,dump_modify,current_balance,update_dict

def users_login():
print("Please log in")
users_username=input("ID(username):<<")
users_password=getpass.getpass("Password:<<")
user_data=open("accounts.json",'r').readlines()
for line in user_data:
user=json.loads(line)
if user['password']==users_password and user['id']==users_username:
if user['status']=='0':
print("Welcome %s" %users_username)
users_menu(user)
else:
print("Account:%s has been locked,please contact Admin"%user['id'])
sys.exit()
print("Invaild ID or Password!")
return users_login()

def users_menu(user_data):
users_list=["Account info","Withdraw","Deposit","Log out"]
print("*****Users menu******")
for count,users_list in enumerate(users_list,1):
print(count,users_list,sep=' ')
users_choice=input("Please select your choice:>>")
if users_choice=='1':
users_view_account(user_data)
elif users_choice=='2':
users_withdraw(user_data)
elif users_choice=='3':
users_deposit(user_data)
else:
sys.exit()

def users_view_account(v_data):
#print(v_data)
current_balance(update_dict(v_data))
#print("Your balance is:",v_data["balance"])
#print("Your credit line is:",v_data["credit"])
return users_menu(update_dict(v_data))

def users_withdraw(withdraw_data):
print("ID:",withdraw_data['id'])
#print("Your balance is:",withdraw_data['balance'])
current_balance(withdraw_data)
withdraw_amount=float(input("How much do you want:>>"))
old_balance=withdraw_data['balance']
if withdraw_amount<=float(old_balance):
new_balance=float(old_balance)-withdraw_amount
#withdraw_data['balance']=new_balance
dump_modify(withdraw_data,withdraw_data['id'],new_balance)
print("Success!")
#print(withdraw_data)
#print("Your new balance is",withdraw_data['balance'])
else:
print("Invaild input! You do not have enough money in your account")
#return users_withdraw(withdraw_data)
return users_menu(update_dict(withdraw_data))

def users_deposit(deposit_data):
print("ID:",deposit_data['id'])
#print("Your balance is:",deposit_data['balance'])
current_balance(deposit_data)
deposit_amount=float(input("Please enter your deposit:>>"))
old_balance=deposit_data['balance']
new_balance=float(old_balance)+deposit_amount
deposit_data['balance']=new_balance
dump_modify(deposit_data,deposit_data['id'],new_balance)
print("Success")
#print("Your new balance is",deposit_data['balance'])
return users_menu(update_dict(deposit_data))

def run_users():
users_login()

4.accounts.py

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#账户信息处理文件(handling the data change)
import os
import sys
import json

def dump_accounts(account_dict):
with open("accounts.json",'a') as f:
data=json.dump(account_dict,f)
f.write('\n')

def dump_modify(account_dict,account_id,amount):
data=open("accounts.json","r").readlines()
n=0
for line in data:
user=json.loads(line)
#print(user)
if n==0:
if user['id']==account_id:
user['balance']=amount
n=open("accounts.json","w")
json.dump(user,n)
n.write("\n")
n.close()
print("your new balance is:",user['balance'])
n=1
if user['id']!=account_id:
n=open("accounts.json","w")
json.dump(user,n)
n.write("\n")
n.close()
n=1
else:
if user['id']==account_id:
user['balance']=amount
n=open("accounts.json","a")
json.dump(user,n)
n.write("\n")
n.close()
print("your new balance is:",user['balance'])
else:
n=open("accounts.json","a")
json.dump(user,n)
n.write("\n")
n.close()


def current_balance(account):
try:
display_current_balance=open("accounts.json",'r').readlines()
for line in display_current_balance:
balance=json.loads(line)
#print(balance)
#print(account)
if balance['id']==account['id']:
print("Your balance is: ",account['balance'])
print("Your credit line is ",account['credit'])
except json.decoder.JSONDecodeError:
print("error!")

def update_dict(acc):
try:
update=open("accounts.json",'r').readlines()
for line in update:
u=json.loads(line)
print(u)
if u['id']==acc['id']:
#print(acc)
return u
except json.decoder.JSONDecodeError:
print("error!")
#admin
def display_accounts():
try:
display=open("accounts.json",'r').readlines()
for line in display:
display_data=json.loads(line)
print(display_data)
except json.decoder.JSONDecodeError:
print("error!")

  • Code
  • Python

扫一扫,分享到微信

微信分享二维码
Python-OOP
Day3-Python-Functions
© 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