Skip to content

Instantly share code, notes, and snippets.

@RaMSFT
Created October 30, 2021 07:28
Show Gist options
  • Select an option

  • Save RaMSFT/eb5f1fc3fe72e0c7c7a749b1f9a054d1 to your computer and use it in GitHub Desktop.

Select an option

Save RaMSFT/eb5f1fc3fe72e0c7c7a749b1f9a054d1 to your computer and use it in GitHub Desktop.
import random
## Define list of operators required
operators = ['+','-','*','/']
## generate random numbers based on random complexity counter
def get_random_numbers(random_complexity):
num1 = random.randint(1, random_complexity)
num2 = random.randint(1, random_complexity)
return num1, num2
## evaluate the result
def check_result(eval_expression):
result = eval(eval_expression)
return result
## Ask question to user and take input
def ask_question(random_numbers, random_op):
eval_string = f"{max(random_numbers)} {random_op} {min(random_numbers)}"
user_answer = input(f"type your answer or type some text to quit - you have 3 attempts - What is the result of {eval_string} ? ")
return user_answer, check_result(eval_string)
#Set the attempts and complexity counter
attempts = 3
## Read previous success attempts, points and complexity
counter_file_name = 'mycounter.csv'
fp = open(counter_file_name,'r')
file_content = list(fp.readline().split(','))
success_attempts = int(file_content[0])
points = int(file_content[1])
start_complexity = int(file_content[2])
fp.close()
## Start to evaluate the user result and increase / decrease the points accordingly
while True:
## Choose a random operator from list of operators
random_op = random.choice(operators)
## Kids can't do non integer divison, so, making sure we ask only integer division
if random_op == '/':
while True:
random_num = get_random_numbers(start_complexity)
check_res = check_result(f"{max(random_num)} {random_op} {min(random_num)}")
if int(check_res) == check_res:
break
else:
random_num = get_random_numbers(start_complexity)
## Give 3 attempts to answer
for val in range(1,attempts+1):
answer = ask_question(random_num, random_op)
print(answer)
if answer[0].isnumeric() == False:
print(f"you choose to exit the program, your total points so far {points}")
exit()
else:
if int(answer[1]) == int(answer[0]):
points += 2
print(f"your answer: {answer[0]} is correct, you earned 2 points, total points {points}")
success_attempts += 1
break
else:
points -= 1
print(f"your answer: {answer[0]} is not correct, you lost 1 point, Total points {points} - attempt {val}")
success_attempts = 1
start_complexity = max(10, start_complexity - 10)
#Decrease the complexity when all 3 attempts are used to answer a question
if success_attempts % 10 == 0 :
start_complexity += 10
fp = open(counter_file_name, 'w')
fp.write(f"{success_attempts},{points},{start_complexity}")
fp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment