Python 基本编程挑战


在本教程中,我们将针对一项挑战撰写解决方案。

挑战

我们必须生成一组随机的基本算术运算。用户将提供问题的数量,而我们必须生成问题。每个问题之后,用户都将回答。在程序结束时,我们必须给出一个分数。让我们试一试。

示例

# importing random and operator modules
import random
import operator
# main function
# taking number of questions that we have to generate
def main(n):
   print("Welcome to the quiz\nYou should answer floats upto 2 decimals")
   # initialising score to 0
   score = 0
   # loop to generate n questions
   for i in range(n):
      # getting answer and correctness of a question
      is_correct, answer = question(i)
      # checking whether is_correct is True or not
      if is_correct:
         # increment score by 1 if correct
         score += 1
         print('Correct Congrats!')
      else:
         # printing the correct answer
         print(f'Incorrect! Answer: {answer}')
   # displaying the total score
   print(f'Total score: {score}')
# function for the question
def question(n):
   # getting answer from the generate_function
   answer = generate_question()
   # taking answer from the user
   user_answer = float(input("Answer: "))
   # returning answer to the main function
   return user_answer == answer, answer
# function to generate a random question
def generate_question():
   # initialising operators for random generation
   operators = {
      '+' : operator.add,
      '-' : operator.sub,
      '*' : operator.mul,
      '/' : operator.truediv,
      '//' : operator.floordiv,
      '%' : operator.mod
   }
   # initialising numbers for expressions
   nums = [i for i in range(10)]
   # getting two random numbers from nums for calculation
   _1, _2 = nums[random.randint(0, 9)], nums[random.randint(0, 9)]
   # generating random operator from the list of operators
   symbol = list(operators.keys())[random.randint(0, 5)]
   # calculating the answer
   answer = round(operators.get(symbol)(_1, _2), 2)
   print(f'{_1} {symbol} {_2}?')
   return answer
if __name__ == '__main__':
   main(5)

输出

如果你运行上面的代码,你将得到以下结果。

Welcome to the quiz
You should answer floats upto 2 decimals
5 + 7?
Answer: 12
Correct Congrats!
9 / 9?
Answer: 1
Correct Congrats!
4 + 7?
Answer: 11
Correct Congrats!
6 // 6?
Answer: 1.0
Correct Congrats!
9 % 3?
Answer: 0
Correct Congrats!
Total score: 5

结论

你还可以添加一些其他功能,比如增加难度、生成从简单的到困难的问题等方式来改进问题……自己尝试一下。我希望你享受本教程。如果你有任何疑问,请在评论部分中指出。

更新于: 2019-11-01

398 浏览

开启您的 职业

通过完成课程获得认证

开始
广告