问题
So I am trying to make a multiple-choice test(it is still in beta right now) and Pycharm does not see a variable/string as defined. It works in codeskulptor.org but not Pycharm. I even tried through Terminal on my mac and still no luck. It gives me the same error "File "", line 1, in NameError: name 'a' is not defined". Can someone please help me with this problem? "a is at "\n(a) are small and simple, lacks a nucleus," this would be the answer to the question. The problem is at "Question(question_prompts[0], "a")" I think because that is where it is defined, right?
import time
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompts = [
"""prokaryotic cells have what characteristics?\n(a) are small and simple, lacks a nucleus,
do not have organells, are a single cell creatures, and have a cell wall.\n\n """
]
questions = [
Question(question_prompts[0], "a")
]
print("Cell Unit Test")
time.sleep(2)
print("10 seconds until test time, take your stuff off your desk")
#time.sleep(10)
print("The test will now commence")
time.sleep(1)
def run_test(questions):
score = 0
for question in questions:
print(question.prompt)
answer = input("Answer:\n ")
if answer == question.answer:
print("Correct!\n")
score += 1
else:
print("Wrong! The correct answer is " + question.answer + "\n")
print("\nEnd of the test.")
print("You got " + str(score) + " out of " + str(len(questions)) + " questions correct")
run_test(questions)
class Question:
def __init__(self, prompt, answer):
self.prompt = prompt
self.answer = answer
question_prompts = [
"""prokaryotic cells have what characteristics?\n(a) are small and simple, lacks a nucleus,
do not have organelles, are single-cell creatures, and have a cell wall.\n\n """
]
questions = [
Question(question_prompts[0], "a")
]
print("Cell Unit Test")
time.sleep(2)
print("10 seconds until test time, take your stuff off your desk")
#time.sleep(10)
print("The test will now commence")
time.sleep(1)
def run_test(questions):
score = 0
for question in questions:
print(question.prompt)
answer = input("Answer:\n ")
if answer == question.answer:
print("Correct!\n")
score += 1
else:
print("Wrong! The correct answer is " + question.answer + "\n")
print("\nEnd of the test.")
print("You got " + str(score) + " out of " + str(len(questions)) + " questions correct")
run_test(questions)'
回答1:
This is Python 3 code, but you're interpreting it using a Python 2 interpreter in Pycharm. You get this error because input in Python 2 has "eval-like" behavior, and it's attempting to literally interpret the "a" you enter as a variable to be referenced.
Change the interpreter you're using in Pycharm to a Python 3 interpreter. Alternatively, you could also change input to raw_input, but judging by the use of print(), this is intended to be run in a Python 3 interpreter.
来源:https://stackoverflow.com/questions/58986129/pycharm-not-seeing-something-as-defined-when-it-is