1+ import random
2+
3+
4+ # Brain Calculator Game
5+ def generate_expression ():
6+ # Generate a random arithmetic expression.
7+ operators = ['+' , '-' , '*' ]
8+ num1 = random .randint (1 , 25 )
9+ num2 = random .randint (1 , 25 )
10+ operator = random .choice (operators )
11+ expression = f"{ num1 } { operator } { num2 } "
12+ return expression
13+
14+
15+ def get_user_name ():
16+ # Get the user's name.
17+ return input ("May I have your name? " )
18+
19+
20+ def play_brain_calc ():
21+ score = 0
22+ round = 3
23+ # Play the Brain Calculator game.
24+ print ("Welcome to the Brain Games!" )
25+ name = get_user_name ()
26+ print (f"Hello, { name } !" )
27+ print ("What is the result of the expression?" )
28+
29+ # Game loop
30+ while score < round :
31+ # Generate a random expression
32+ expression = generate_expression ()
33+ print (f"Question: { expression } " )
34+ # Calculate the correct answer
35+ correct_answer = eval (expression )
36+ # Check user input
37+ while True :
38+ user_answer_str = input ("Your answer: " ).strip ()
39+ if user_answer_str .lstrip ('-' ).isdigit ():
40+ user_answer_num = int (user_answer_str )
41+ user_answer = user_answer_num
42+ break
43+ else :
44+ print ("Please enter a valid integer." )
45+ # Check if the answer is correct
46+ if user_answer == correct_answer :
47+ score += 1
48+ print ("Correct!" )
49+ else :
50+ score = 0
51+ print (f"'{ user_answer } ' is wrong answer ;(. Correct answer was '{ correct_answer } '." )
52+ print (f"Let's try again, { name } " )
53+ print (f"Congratulations, { name } !" )
0 commit comments