-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofessor.py
More file actions
72 lines (57 loc) · 2.76 KB
/
professor.py
File metadata and controls
72 lines (57 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""
One of David’s first toys as a child, funny enough, was Little Professor, a “calculator” that would generate ten different math problems for David to solve. For instance, if the toy were to display 4 + 0 = , David would (hopefully) answer with 4. If the toy were to display 4 + 1 = , David would (hopefully) answer with 5. If David were to answer incorrectly, the toy would display EEE. And after three incorrect answers for the same problem, the toy would simply display the correct answer (e.g., 4 + 0 = 4 or 4 + 1 = 5).
In a file called professor.py, implement a program that:
Prompts the user for a level, n. If the user does not input 1, 2, or 3, the program should prompt again.
Randomly generates ten (10) math problems formatted as X + Y = , wherein each of X and Y is a non-negative integer with n digits. No need to support operations other than addition (+).
Prompts the user to solve each of those problems. If an answer is not correct (or not even a number), the program should output EEE and prompt the user again, allowing the user up to three tries in total for that problem. If the user has still not answered correctly after three tries, the program should output the correct answer.
The program should ultimately output the user’s score: the number of correct answers out of 10.
Structure your program as follows, wherein get_level prompts (and, if need be, re-prompts) the user for a level and returns 1, 2, or 3, and generate_integer returns a randomly generated non-negative integer with level digits or raises a ValueError if level is not 1, 2, or 3:
"""
import random
def main():
level = get_level()
score = 0
for _ in range(10):
x, y = generate_integer(level)
solution = x + y
prompt = f"{x} + {y} = "
answer = get_answer(prompt, solution)
if answer:
score += 1
print(f"Score: {score}")
def get_level():
while True:
try:
level = int(input("Level: "))
if 1 <= level <= 3:
return level
except ValueError:
pass
def generate_integer(level):
if level == 1:
x = random.randint(0, 9)
y = random.randint(0, 9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def get_answer(prompt, solution):
tries = 0
while tries < 3:
try:
problem = int(input(prompt))
if problem == solution:
return True
else:
print("EEE")
tries += 1
except ValueError:
print("EEE")
tries += 1
print(prompt, solution)
return False
if __name__ == "__main__":
main()