In: Computer Science
I need this program in Paython programing language
wants to maintain a list of quiz Questions, refer to as their Question Pool, in an external data file. Each Question should have the question text, point value, four answer choices, and the correct answer stored. Since they want to keep it fun, each question should also store witty retorts given as Feedback text to the user along with the answer.
The application should have a Graphical User Interface (GUI), which allows the user to see a list of questions. A question editor should allow the users to add new questions, view existing question details, modify existing questions, and delete existing questions.
The program should be able to save and load the list of questions to/from disk storage using files. The user should then be able to perform the standard operations of adding questions, modifying existing questions, and deleting existing questions.
For the quizzing mechanism, A simple 1-person Quiz within the program with 3 questions chosen from the pool of questions. A menu option should allow the user to start a new Quiz, which should clear the application’s main window of everything except the quiz. After completing a Quiz, the user must be allowed to continue using any operation the application offers including taking another Quiz or Managing questions. Your program should not exit or end unless the user chooses to close the program.
# The "pass" command tells Python to "do nothing".
# It is simply a placeholder to ensure that the starter files run
smoothly.
# They are not needed in your completed program.
# Import the json module to allow us to read and write data in JSON
format.
import json,os
#global current_ques_list
#current_ques_list = []
# This function repeatedly prompts for input until an integer is
entered.
def inputInt(prompt):
while True:
try:
temp = int(input(prompt))
return temp
except:
continue
# This function repeatedly prompts for input until something other
than whitespace is entered.
# See Point 2 of the "Functions in admin.py" of the brief
def inputSomething(prompt):
global data_list
question = input(prompt)
return question
# This function opens "data.txt" in write mode and writes dataList
to it in JSON format.
# See Point 3 of the "Functions in admin.py" section of the
brief.
def saveChanges(dataList):
with open('data.txt', 'w') as outfile:
json.dump(dataList, outfile)
# Here is where you attempt to open data.txt and read the data into
a "data" variable.
# If the file does not exist or does not contain JSON data, set
"data" to an empty list instead.
# This is the only time that the program should need to read
anything from the file.
# Print welcome message, then enter the endless loop which prompts
the user for a choice.
# See Point 2 of the "Requirements of admin.py" section of the
brief.
# The rest is up to you.
print('Welcome to the Quizle Admin Program.')
with open('data.txt','r') as data_file:
data_text_file = json.load(data_file)
current_ques_list = []
while True:
data_list = []
print('Choose [a]dd, [l]ist, [s]earch, [v]iew, [d]elete or
[q]uit.')
choice = input('> ').strip()
try:
if(type(choice)!='str'):
raise Exception
except Exception:
if choice == 'a':
# Add a new question.
# See Point 3 of the "Requirements of admin.py" section of the
brief.
question = str(inputSomething("Enter the question:
").strip()).lower()
while True:
if(question == ""):
question =str(inputSomething("Enter the question:
").strip()).lower()
else:
break
answer = []
while True:
x = str(input("Enter a valid answer (enter 'q' when
done):").strip()).lower()
if(x==''):
continue
elif(x!='' and x!='q'):
answer.append(x)
elif(x=='q' and len(answer)!=0):
break
temp = inputInt('Enter question difficulty (1-5)')
while True:
if(temp < 1 or temp >5):
print("Invalid value. Must be an integer between 1 and 5")
temp = inputInt('Enter question difficulty (1-5)')
else:
break
diff = temp
final_object =
{'question':question,'answer':answer,'diff_level':diff}
data_list.append(final_object)
current_ques_list.append(final_object)
if(os.stat("data.txt").st_size == 0):
saveChanges(data_list)
else:
#with open('data.txt','r') as data_file:
# data = json.load(data_file)
#print(data_text_file)
for i in data_list:
data_text_file.append(i)
saveChanges(data_text_file)
elif choice == 'l':
# List the current questions.
# See Point 4 of the "Requirements of admin.py" section of the
brief.
if(len(current_ques_list)==0):
print("No questions saved")
else:
print("Current Question:")
for i in range(0,len(current_ques_list)):
print('\t',i+1,")",current_ques_list[i]['question'])
elif choice == 's':
# Search the current questions.
# See Point 5 of the "Requirements of admin.py" section of the
brief.
search_term = inputSomething("Enter a search term: ").strip()
for i in range(len(current_ques_list)):
if search_term in current_ques_list[i]['question']:
print("Search results:")
print('\t',i+1,')',current_ques_list[i]['question'])
elif choice == 'v':
# View a question.
# See Point 6 of the "Requirements of admin.py" section of the
brief.
view_index = inputInt('Question number to view: ')
try:
req_data = current_ques_list[view_index-1]
print("Question:")
print("\t",req_data['question'])
print("\t","Valid Answers: ",', '.join(req_data['answer']))
print("\t","Difficulty: ",req_data["diff_level"])
except:
print("Invalid index number")
elif choice == 'd':
# Delete a question.
# See Point 7 of the "Requirements of admin.py" section of the
brief.
try:
del_index = int(inputInt('Question number to delete: '))-1
if(del_index+1>len(current_ques_list)):
print("Invalid index number")
else:
del_question = current_ques_list.pop(del_index)
#saveChanges(current_ques_list)
#with open('data.txt','r') as data_file:
# temp_list = json.load(data_file)
#print(data_text_file)
for i in range(len(data_text_file)):
if(data_text_file[i]['question']==del_question['question']):
del data_text_file[i]
try:
#print('try',data_text_file)
with open('data.txt', 'w') as outfile:
json.dump(data_text_file, outfile)
except:
print("Invalid index number")
except:
pass
elif choice == 'q':
# Quit the program.
# See Point 8 of the "Requirements of admin.py" section of the
brief.
print("GoodBye!")
break
else:
# Print "invalid choice" message.
# See Point 9 of the "Requirements of admin.py" section of the
brief.
print("Invalid choice")
continue
____________________________________________________________________________________________
data.txt
[{"diff_level": 2, "question": "who is pm of india ?", "answer":
["narendra modi"]}, {"diff_level": 2, "question": "who is president
of usa?", "answer": ["donald trump"]}, {"diff_level": 4,
"question": "what is capital of netherland?", "answer":
["stockholmes"]}, {"diff_level": 2, "question": "who is cm of
delhi?", "answer": ["kejriwal"]}, {"diff_level": 4, "question":
"who is rocky marciano?", "answer": ["boxer"]}]
____________________________________________________________________________________________
quizle.py
# The "pass" command tells Python to do nothing. It is simply a
placeholder to ensure that the starter files run smoothly.
# They are not needed in your completed program. Replace them with
your own code as you complete the assignment.
# Import the required modules.
from tkinter import *
from tkinter import messagebox
import json
import random
class ProgramGUI:
def __init__(self,master):
# This is the constructor of the class.
# It is responsible for loading and reading the data file and
creating the user interface.
# See Points 1 to 6 "Constructor of the GUI Class of quizle.py"
section of the brief.
self.master = master
master.title("Quizle")
master.minsize(width=400,height=150)
frame = Frame(master)
frame.pack()
try:
with open('data.txt','r') as data_file:
self.data = json.load(data_file)
except:
print("Missing/Invalid file")
master.destroy()
return
if len(self.data)<5:
messagebox.showerror("Error","Insufficient number of
questions")
master.destroy()
return
self.user_score = 0
self.no_of_question_answered = 0
self.correct_question = 0
self.instance = 0
self.diff_level_value = 0
self.diifficulty_level = Label(frame)
self.diifficulty_level.grid(row=1,columnspan=2,padx=20,pady=10)
self.question = Label(frame)
self.question.grid(row=2,columnspan=2,padx=20,pady=10)
self.question_entry = Entry(frame)
self.question_entry.grid(row=3)
self.button = Button(frame,text="Submit
Answer",command=self.checkAnswer)
self.button.grid(row=3,column=1)
self.question_status = Label(frame)
self.question_status.grid(row=4,columnspan=2,padx=20,pady=10)
self.loadQuestion()
def loadQuestion(self):
# This method is responsible for displaying a question in the
GUI,
# as well as showing the special message for difficult questions
and showing the user's current progress
# See Point 1 of the "Methods in the GUI Class of quizle.py"
section of the brief.
self.question_entry.focus_set()
if self.instance == 0:
self.current_question_set = random.sample(self.data,5)
question = random.choice(self.current_question_set)
self.current_question = question['question']
self.diff_level_value = int(question['diff_level'])
if(int(question['diff_level'])>=4):
self.diifficulty_level.grid(row=1,columnspan=2,padx=20,pady=10)
self.diifficulty_level.config(text="This is a hard one - good
luck!",fg="blue")
else:
self.diifficulty_level.grid_forget()
self.question.config(text=self.current_question)
self.question_status.config(text="%s/%s questions answered
correctly"%(self.correct_question,self.no_of_question_answered))
self.question_answer = question['answer']
self.current_question_set.remove(question)
print(self.current_question_set)
def checkAnswer(self):
# This method is responsible for determining whether the user's
answer is correct and showing a Correct/Incorrect messagebox.
# It also checks how many questions have been asked to determine
whether or not to end the game.
# See Point 2 of the "Methods in the GUI Class of quizle.py"
section of the a brief.
self.no_of_question_answered += 1
if type(self.question_entry.get()) == str:
user_answer = str(self.question_entry.get()).lower()
else:
user_answer = self.question_entry.get()
if user_answer in self.question_answer:
self.correct_question +=1
self.user_score +=self.diff_level_value*2
messagebox.showwarning("Correct","You are correct!")
else:
messagebox.showerror("Incorrect","Sorry,that was incorrect!")
print('ques',self.no_of_question_answered)
if self.no_of_question_answered == 5:
print('yo:',self.no_of_question_answered)
messagebox.showwarning("Final Score","Game Over \n Final Score: %s
\n\n Thanks for playing" %(self.user_score))
self.master.destroy()
else:
self.instance +=1
self.question_entry.delete(0, 'end')
self.loadQuestion()
# Create an object of the ProgramGUI class to begin the
program.
root = Tk()
gui = ProgramGUI(root)
root.mainloop()