python - Python - 寻找一种方法来提高效率
问题描述
我对 python 比较陌生,我正在寻找一种方法来提高这段代码的效率。谢谢!
import random
import string
import time
ques = []
anss = []
nums = string.digits
def que():
for i in range(10):
num0 = random.choice(nums)
num1 = random.choice(nums)
ans = num0 + '+' + num1
ques.append(ans)
ans = int(num0) + int(num1)
anss.append(ans)
global length
length = len(ques)
def main():
global counter
counter = 0
for i in range(10):
global answer
answer = int(input('What is ' + ques[i] + '?\n>>'))
if answer == anss[i]:
print('Correct!')
counter += 1
else:
print('Wrong!')
def score():
x = str((counter / length*100))
x = 'You got ' + x + '%'
return x
if __name__ == '__main__':
que()
main()
time.sleep(0.5)
print('Please wait while we calculate your score.')
time.sleep(1)
print(score())
之前,我尝试将答案和问题放在一个列表中 - 但在一个循环之后,它会在索引中添加一个,如下所示。
for i in range(10):
if answer == questions[i+1]:
print('correct')
i += 1 #This is meant to skip the answer part of the list and goto the next question but i couldnt get it to work.
解决方案
嗯......我只是改变你的得分方法
def score():
return 'You got ' + str((counter / length*100)) + '%'
为了返回完整的字符串并避免x
变量。
推荐阅读
- asp.net-core-mvc - 删除过滤器而不更改代码
- java - 如何使用 mockito 模拟返回未来 java 对象的方法
- javascript - 如何从 Javascript 或 jquery 或 MVC4 获取客户端机器 MAC 地址?
- android - 如何在片段上设置深色叠加层
- javascript - 带有输入、按钮和图片的 Javascript 动态表
- javascript - 我收到未定义的 javascript 警报
- linux - 无法对远程服务器进行 SSH。错误:ssh_exchange_identification:读取:对等方重置连接
- ruby-on-rails - “错误”部分适用于“新”用户,但不适用于“编辑”用户
- powershell - HTML 到 CSV 文件的转换
- powershell - 触发远程powershell脚本独立运行