请教如何把代码装封在函数或者类里面呢?
下面代码如何装封会比较好呢?有什么好的装封思路呢?求大神指导一下,十分感谢!import requests
import json
print('''
5分钟,评估你的单词量
评估过程包括三步:
1. 选择适合你的出题范围
2. 通过50个单词得到你的大致词汇量范围
3. 检验你是否真的掌握你在第二步中选择的单词''')
url = 'https://www.'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
res = requests.get(url,headers=headers)
words = res.json()
list = []
types = words['data']
for type in types:
list.append(type[0])
print('''请输入你选择的词库编号,按Enter确认
1,GMAT 2,考研 3,高考 4,四级 5,六级
6,英专 7,托福 8,GRE 9,雅思 10,任意
''')
choice = int(input('>'))
choice = list[choice-1]
print(choice)
test = requests.get('https://www.'+choice,headers=headers)
test_json = test.json()
test_word = []
words_know = []
not_know = []
n = 0
for i in test_json['data']:
danci = i['content']
n = n + 1
print(f'\n第{n}个单词{danci}是否认识,如果认识请按y,如果不认识请按n,输入Esc结束此阶段')
answer = input('>')
if answer == 'y':
test_word.append(danci)
words_know.append(i)
elif answer == 'n':
not_know.append(i)
elif answer == 'Esc':
break
else:
print('\n输入错误,请按提示输入。')
right = 0
wrong = []
for i in words_know:
print('--------------------------------')
print('A.'+ i['definition_choices'][0]['definition'])
print('B.'+ i['definition_choices'][1]['definition'])
print('C.'+ i['definition_choices'][2]['definition'])
print('D.'+ i['definition_choices'][3]['definition'])
xuan = input('请输入你的选择:')
print('--------------------------------\n')
dic = {'A':i['definition_choices'][0]['pk'],'B':i['definition_choices'][1]['pk'],'C':i['definition_choices'][2]['pk'],
'D':i['definition_choices'][3]['pk']}
if dic[xuan] == i['pk']:
right = right + 1
else:
wrong.append(i['content'])
print('本次测试小结:')
print(f'50个单词里面,有{len(test_word)}单词你是认识,有'+str(50-int(len(test_word)))+f'单词你是不认识的,在认识的单词里面,你做对了{right}个,做错了'+str(right-int(len(test_word)))+'个,请继续努力!')
[此贴子已经被作者于2020-2-3 12:30编辑过]