Question

In: Computer Science

I need this program in  Paython programing language wants to maintain a list of quiz Questions, refer...

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.

Solutions

Expert Solution

# 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()


Related Solutions

in C++ programing language Write a program that prompts the user for an integer, then prints...
in C++ programing language Write a program that prompts the user for an integer, then prints all of the numbers from one to that integer, separated by spaces. Use a loop to print the numbers. But for multiples of three, print "Fizz" instead of the number, and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". Drop to a new line after printing each 20 numbers. If the user typed...
I need programing in C language (not C#,C++) Sheldon Game RPSLS: - Stone: Win against Scissors...
I need programing in C language (not C#,C++) Sheldon Game RPSLS: - Stone: Win against Scissors who destroys and against Lizard who bursts,ties with himself, and loses to Rock Covering Paper and Spock that vaporizes the stone. - Role: Win against Stone who he covers and against Spock who refutes, tie with himself, and loses against Scissors who cut it and against Lizard who eat. - Scissors: Win against Paper who cuts and against Lizard who decapitates, tie with himself,...
c programing language When a new program is executed, a new process is created with the...
c programing language When a new program is executed, a new process is created with the next available process ID. However, there are a few special processes that always have the same process ID, which are usually given the ID value less than 5 these are called system processes. Can you identify which of the two system processes have the process ID of 0 and 1 respectively?
Programing Language: Java The Problem: You are writing a program that encrypts or decrypts messages using...
Programing Language: Java The Problem: You are writing a program that encrypts or decrypts messages using a simple substitution cipher. Your program will use two constant strings. One will represent the code for encryption: going from the original message (called the plaintext) to the encrypted version of the message. The other will be “abcdefghijklmnopqrstuvwxyz” (the lowercase alphabet. Your program will ask the user whether they want to 1) encrypt a message, 2) decrypt a message, or 3) quit. If they...
Using the programing language of Verilog I attempted to make a counter to count from 0...
Using the programing language of Verilog I attempted to make a counter to count from 0 to 9 then loop back to 0 using the internal clock of the FPGA cyclone IV from altera. the code is posted at the bottom I get the following errors Error (10663): Verilog HDL Port Connection error at Encryption.v(9): output or inout port "clk" must be connected to a structural net expression Error (10285): Verilog HDL Module Instantiation error at Encryption.v(9): instance "" specifies...
Need a program in java that creates a random addition math quiz The program should ask...
Need a program in java that creates a random addition math quiz The program should ask the user to enter the following The smallest and largest positive numbers to be used when generating the questions - The total number of questions to be generated per quiz - The total number of the quiz's to create from then the program should generate a random math (Just addition) quiz from what the user entered
I need a program(code) in any programming language that performs the following operations: union, concatenation and...
I need a program(code) in any programming language that performs the following operations: union, concatenation and conversion DFA-NDFA.
C++ Create a program that use the linkedbag 3. Develop a program to maintain a list...
C++ Create a program that use the linkedbag 3. Develop a program to maintain a list of homework assignments. When an assignment is assigned, add it to the list, and when it is completed, remove it. You should keep track of the due date. Your program should provide the following services: • Add a new assignment. • Remove an assignment. • Provide a list of the assignments in the order they were assigned. • Find the assignment(s) with the earliest...
I need a MIPS Assembly program that "Display the elements of the linked list in reverse...
I need a MIPS Assembly program that "Display the elements of the linked list in reverse order." It needs subprogram and those subprogram does not have t registers.
I need to add the following to this program 1) Alphabetically sort the list of entries...
I need to add the following to this program 1) Alphabetically sort the list of entries by name (first or last). 2) Find a phone number for a given name. 3) Randomly select a friend from the phonebook for you to call. 4) Delete everyone from the phonebook at the same time. #include <stdio.h> #include<string.h> #include <ctype.h> #include<stdlib.h> typedef struct contact { char firstname[20]; char lastname[20]; char phoneNumber[15]; struct contact * next; struct contact * prev; }contact; typedef enum {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT