首页 > 解决方案 > 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.
 

标签: python

解决方案


嗯......我只是改变你的得分方法

def score():
   return 'You got ' + str((counter / length*100)) + '%'

为了返回完整的字符串并避免x变量。


推荐阅读