File "C:\Projects\Python\MathGame\Game.py", line 26, in <module> if ask_question(): ^^^^^^^^^^^^^^ File "C:\Projects\Python\MathGame\Game.py", line 20, in ask_question answer = random_problem() ^^^^^^^^^^^^^^^^ File "C:\Projects\Python\MathGame\Game.py", line 6, in random_problem '+': operator.add, ^^^^^^^^ UnboundLocalError: cannot access local variable 'operator' where it is not associated with a value PS C:\Projects\Python\MathGame>
AmirHossein۱۶ اسفند ۱۴۰۳، ۱۱:۴۵
بخاطر استفاده از operator.keys() هست. علتش اینه که operator یک دیکشنری با کلیدهای قابل دسترسی نیست، و یک ماژوله که توابعش مستقیماً باید فراخوانی بشن. عملگرها رو در یک لیست بذار و با random.choice ازشون استفاده کن.
import random
import operator
def random_problem():
operators = [operator.add, operator.sub, operator.mul, operator.truediv]
op = random.choice(operators)
n1 = random.randint(1, 10)
n2 = random.randint(1, 10)
if op == operator.truediv and n2 == 0:
n2 = 1
answer = op(n1, n2)
print(f"{n1} {['+', '-', '*', '/'][operators.index(op)]} {n2}")
return answer
def ask_question():
answer = random_problem()
canswer = float(input(""))
return answer == canswer
score = 0
while True:
if ask_question():
score += 1
print("OK!")
else:
print("NOK!")
print("break") # فقط بعد از NOK چاپ میشه
print(f"GameOver!!! score: {score}") # فقط بعد از NOK چاپ میشه
break