Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

기본 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

결론

난이도 증가, 쉬운 문제부터 어려운 문제 생성 등과 같은 기능을 추가하여 문제를 개선할 수도 있습니다. 직접 시도해 보세요. 튜토리얼을 즐겼기를 바랍니다. 궁금한 점이 있으면 댓글 섹션에 언급하세요.