нужно оптимизировать код
Я еще учусь программировать на питоне и поэтому я решил написать большую программу вопросник в которую можно играть или вкладывать свои вопросы. От вас я прошу только говорить мои ошибки которые вы заметите и желательно писать их решение. Ну или просто сделать его более читабельным
from random import randint
import sys
voprosi = {1:["q1","почему ты в это играешь? ",["хочу создать новые вопросы","хочу оптимизировать работу программы","просто так"],1],
2:["q4","почему вопрос четвертый если он обозначен как 2?",["автор еще не исправил этот баг","автор не будет ничего исправлять","ой все фигня ваш тест"],1]}
i = 1
def ad(): # команда для создания вопроса
answ_vars = []
tit = input("write a title of question: " ) # беру тему вопроса
vopros = input("write vopros: " ) # сам вопрос
print("write some answers")
print("write 'ok' when it is complete!")
while True: # пишем ответы
sss = input()
if sss != "ok":
answ_vars.append(sss)
continue
else:
print("выберите правильный ответ")
for f,s in enumerate(answ_vars): # для написанных ответов выбрать правильный вариант
print(f,s)
right_answ = int(input())
while right_answ > len(answ_vars)-1 or right_answ < 0: # когда правильный ответ не в диапазоне, вылезает ошибка
print("неверный ввод")
right_answ = int(input())
print("otlichna!")
global voprosi # хз что это наверно надо
i = len(voprosi)+1
voprosi[i] = [tit,vopros,answ_vars,right_answ] # помещаем все под одни скобки
print(voprosi[i]) # финальный вид вопроса
break
def quiz(): # команда для игры
if len(voprosi)<2: # при вопросах меньше 2х возникает ошибка изза рандома)
print("make more questions!!! ")
return "Sucker"
v = voprosi[randint(1,len(voprosi))]
print("title: "+v[0])
print("question: "+v[1])
for k,g in enumerate(v[2]):
print(k, "• "+g)
while True:
if int(input()) == v[3]:
print("nice! ")
break
else:
print("try again" )
def quig():
sys.exit()
def popored(red=0,popo=0,item=0):
if red == 1: # редактирование вопроса в процессе разработки:)
pass
elif popo == 1: # удаление вопроса
for i,t in enumerate(voprosi):
print(i,voprosi[t])
print("What number?: ")
while True:
p = int(input())
if p not in range(len(voprosi)):
print("choose an existing number")
continue
else:
del voprosi[p]
print(voprosi.items())
elif item == 1:
print(voprosi.items())
print("create some questions or complete it! ")
while True:
a = input("введите START для игры, AD для добавления вопроса или QUIT для выхода: " )
print("\n")
if a == "quit".lower():
quig() #выходим
elif a == "start".lower():
quiz() #пробуем играть
elif a == "ad".lower():
ad() #запускаем функцию для добавления вопроса
elif a == "popo":
popored(popo=1) #удаление вопроса
elif a == "item":
popored(item=1) #показ вопросов
Ответы (1 шт):
Автор решения: NEWME0
→ Ссылка
import sys
import random
questions = [
{
'title': 'question_1_title',
'text': 'querstion_1_text?',
'answers': [
'answer 1',
'answer 2',
'answer 3',
'answer 4',
],
'correct': 1,
},
{
'title': 'question_2_title',
'text': 'querstion_2_text?',
'answers': [
'answer 1',
'answer 2',
'answer 3',
'answer 4',
],
'correct': 2,
},
]
def add_question():
# Dialog for adding questions
title = input("Write a title for question: ")
text = input("Write question: ")
print("Write answers: ")
print("Write OK when is complete")
answers = list()
answer = input("Write answer: ")
while answer.lower() != 'ok':
answers.append(answer)
answer = input("Write one more answer: ")
correct = input("Choice right answer: ")
correct = int(correct)
while 0 > correct > len(answers):
correct = input("Wrong input try again: ")
correct = int(correct)
question = {
'title': title,
'text': text,
'answers': answers,
'correct': correct,
}
questions.append(question)
def del_question():
NotImplemented
def lst_question():
# List questions
for question in questions:
print(question['title'])
print(question['text'])
for answer in question['answers']:
print(' ', answer)
print(question['correct'])
print('')
def ask_question():
# Ask a question
question = random.choice(questions)
print(question['title'])
print(question['text'])
for i, answer in enumerate(question['answers']):
print('{0} - {1}'.format(i, answer))
respons = input("Input your respons: ")
respons = int(respons)
while respons != question['correct']:
respons = input("Try again: ")
respons = int(respons)
print('Excelent!!!')
def end():
sys.exit()
def main():
actions = {
'add': add_question,
'del': del_question,
'lst': lst_question,
'ask': ask_question,
'end': end,
}
print("Create some questions or complete it!")
print("ADD для добавления вопроса")
print("DEL для удаления вопроса")
print("LST для показа вопросов")
print("ASK для игры")
print("END для выхода")
while True:
command = input('Input command: ')
action = actions.get(command.lower())
if not action:
print('Incorect command')
continue
action()
if __name__ == '__main__':
main()
Удачи тебе в твоих начинаниях.