Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reset list if user regrets
#1
Question 
Hi again :)

I took some time to work on the input validation of my code before I convert it to Classes and I can't understand why the program ends if the user regrets his first answer and choose another.

help?

He're the full code this time:

def get_questions(question):
    while True:

        try:
            question = str(input("Enter your question: "))
            if len(question) == 0:
                raise ValueError

            elif question[0] == ' ':
                raise ValueError

            break

        except ValueError:
            print(f"[!]Error! '{question}' is Invalid.")

    question_list.append(question)
    return question


def get_question_score(qs):
    while True:
        try:
            qs = int(input("Enter Question Score: "))
            if not float(qs):
                raise ValueError

            elif qs + (sum(scores)) > 100:
                print(f"{qs + sum(scores)} > 100")
                raise ValueError
            break

        except ValueError:
            print(f"Debug | qs={qs}")
            scores_local.clear()
            print(f"[!]Error! Invalid Input. Try Again.")

    scores_local.append(qs)
    scores.append(qs)
    return True


def get_number_of_answers(num=None, minv=None, maxv=None):
    print(f"\tMin={minv} | Max={maxv}")
    while True:
        try:
            num = int(input(f"Number of Answers [{minv}-{maxv}]: "))
            if minv and minv > num:
                print(f"[!]Error! {num} < {minv}")
                raise ValueError

            if maxv and maxv < num:
                print(f"[!]Error! {num} > {maxv}")
                raise ValueError

            answers_local.append(num)
            answers_local.pop(0)
            break

        except ValueError:
            print("[!]Input Not Valid")

    return num


def get_answers(num_of_answers, answer):

    try:
        for ans in range(1, num_of_answers+1):  # Start Index from 1.
            answer = input(f"Answer #{ans}: ")
            if len(answer) == 0:
                raise ValueError

            if answer[0] == ' ':
                raise ValueError

            answers_local.append(answer)

    except ValueError:
        print("Error! No Input!")
        answers_local.clear()
        get_answers(num_of_answers, answer="")

    number_of_answers[0] = num_of_answers
    return answer


def get_right_answer_number(num, is_right=False):
    print(f"Debug | RightAnswerNumber: {num}")  # Debug
    while True:
        try:
            num = int(input("[?]Right Answer #: "))
            if not float(num):
                raise ValueError

            if 0 < num <= number_of_answers[0]:
                is_right = True
                break
            else:
                raise ValueError

        except ValueError:
            print("[!]Error! Invalid Input.")

    right_answer_number.append(num)
    return is_right


def ask_if_sure(ans):   # Returns True

    print(f"Debug | RightAnswerNum1st: {right_answer_number}")
    ask_sure = input("Are you sure? [Y/n]: ")
    if ask_sure.lower() == "n":
        right_answer_number.clear()
        print(f"Debug | RightAnswerNumber-N-: {right_answer_number}")
        right_answer_number[0] = 0
        get_right_answer_number(num=0)

    elif ask_sure.lower() == "y":
        return True

    else:
        print("Error! Please type [Y/n]")
        ask_if_sure(ans="")


def ask_continue():
    while True:

        a_continue = input("Do you wish to add more questions? [Y/n]: ")
        if a_continue.lower() == "y":
            break

        elif a_continue.lower() == "n":
            return False

        else:
            print("Error! Please choose [Y/n]")

    return True


def restart():

    answers_local.clear()
    right_answer_number.clear()
    scores_local.clear()
    main(question="", question_score=0, num_of_answers=0)


def finish():
    print("\n\n==============RESULTS==============\n")
    print("#\t Question\t Answer\t\t Score")
    number_of_questions = len(question_list)
    for num in range(number_of_questions):
        print(f"{num+1}\t {question_list[num]}\t\t\t {answers[num]}\t\t\t\t {scores[num]}")


def main(question, question_score, num_of_answers):

    question = get_questions(question)
    print(f"Debug | QuestionList: {question_list}")
    question = question_list[-1]
    is_big = get_question_score(question_score)
    while is_big:
        num_of_answers = get_number_of_answers(num=0, minv=2, maxv=4)
        multiple_answers = get_answers(num_of_answers, answer="")
        print(f"Multiple Answer: {answers_local}")
        print(f"NumOfAnswers: {number_of_answers}")    # Debug
        is_right = get_right_answer_number(num=len(answers_local))
        print("\n****     Summery     ****")
        print(f"Question: {question_list[-1]}\nAnswers: {answers_local}\nRight Answer: {right_answer_number[0]}")
        print(f"Question score: {scores_local}, Total Score: {sum(scores)}, Valid: {is_big}")
        while not is_right:
            is_right = get_right_answer_number(num=len(answers_local))
            right_answer_number[0] = 0

        while is_right:
            sure = ask_if_sure(ans="")
            answers.append(right_answer_number[0])

            while sure:
                print(f"Debug | answers: {answers}")

                ask_if_continue = ask_continue()
                if not ask_if_continue:
                    finish()

                while ask_if_continue:
                    restart()
                    break
                break
            break
        break


if __name__ == "__main__":

    question_list = []
    scores_local = []
    scores = []
    number_of_answers = [0]
    answers_local = []
    answers = []
    right_answer_number = []

    main(question="", question_score=0, num_of_answers=0)
This is input for right answer:

def get_right_answer_number(num, is_right=False):
    print(f"Debug | RightAnswerNumber: {num}")  # Debug
    while True:
        try:
            num = int(input("[?]Right Answer #: "))
            if not float(num):
                raise ValueError

            if 0 < num <= number_of_answers[0]:
                is_right = True
                break
            else:
                raise ValueError

        except ValueError:
            print("[!]Error! Invalid Input.")

    right_answer_number.append(num)
    return is_right
here's the are u sure input function:

def ask_if_sure(ans):   # Returns True

    print(f"Debug | RightAnswerNum1st: {right_answer_number}")
    ask_sure = input("Are you sure? [Y/n]: ")
    if ask_sure.lower() == "n":
        right_answer_number.clear()
        print(f"Debug | RightAnswerNumber-N-: {right_answer_number}")
        right_answer_number[0] = 0
        get_right_answer_number(num=0)

    elif ask_sure.lower() == "y":
        return True

    else:
        print("Error! Please type [Y/n]")
        ask_if_sure(ans="")
And the main() and if __name__ ....
def main(question, question_score, num_of_answers):

    question = get_questions(question)
    print(f"Debug | QuestionList: {question_list}")
    question = question_list[-1]
    is_big = get_question_score(question_score)
    while is_big:
        num_of_answers = get_number_of_answers(num=0, minv=2, maxv=4)
        multiple_answers = get_answers(num_of_answers, answer="")
        print(f"Multiple Answer: {answers_local}")
        print(f"NumOfAnswers: {number_of_answers}")    # Debug
        is_right = get_right_answer_number(num=0)
        print("\n****     Summery     ****")
        print(f"Question: {question_list[-1]}\nAnswers: {answers_local}\nRight Answer: {right_answer_number[0]}")
        print(f"Question score: {scores_local}, Total Score: {sum(scores)}, Valid: {is_big}")
        while not is_right:
            is_right = get_right_answer_number(num=len(answers_local))
            right_answer_number[0] = 0

        while is_right:
            sure = ask_if_sure(ans="")
            answers.append(right_answer_number[0])

            while sure:
                print(f"Debug | answers: {answers}")

                ask_if_continue = ask_continue()
                if not ask_if_continue:
                    finish()

                while ask_if_continue:
                    restart()
                    break
                break
            break
        break


if __name__ == "__main__":

    question_list = []
    scores_local = []
    scores = []
    number_of_answers = [0]
    answers_local = []
    answers = []
    right_answer_number = [0]

    main(question="", question_score=0, num_of_answers=0)
Thank you for your time!
Reply
#2
Fixed!

def ask_if_sure(ans):   # Returns True
    while True:

        print(f"Debug | RightAnswerNum1st: {right_answer_number[0]}")
        ask_sure = input("Are you sure? [Y/n]: ")
        if ask_sure.lower() == "n":
            print(f"Debug | RightAnswerNumber-N-: {right_answer_number[0]}")
            get_right_answer_number(num=len(answers_local))

        elif ask_sure.lower() == "y":
            break

        else:
            print("Error! Please type [Y/n]")
            ask_if_sure(ans="")

    answers.append(right_answer_number[0])
    return True
forgot to append the answer to the answers list and deleted the list.clear in main() :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  user input values into list of lists tauros73 3 1,072 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  functional LEDs in an array or list? // RPi user Doczu 5 1,603 Aug-23-2022, 05:37 PM
Last Post: Yoriz
  User-defined function to reset variables? Mark17 3 1,651 May-25-2022, 07:22 PM
Last Post: Gribouillis
  Looking for a way to loop until user enters from a list? PythonW19 7 3,362 Mar-21-2021, 08:56 PM
Last Post: PythonW19
  User input/picking from a list AnunnakiKungFu 2 2,335 Feb-27-2021, 12:10 AM
Last Post: BashBedlam
  cannot reset list in for loop bstanard 3 3,738 Feb-28-2020, 01:24 AM
Last Post: jefsummers
  Help with calling list from user input farispython 5 2,820 Nov-03-2019, 03:13 PM
Last Post: Gribouillis
  Creating csv header from user-input list dvanommen 2 2,151 Aug-26-2019, 08:51 PM
Last Post: dvanommen
  User input - list Ondra 3 2,667 Feb-15-2019, 11:29 AM
Last Post: Larz60+
  How do I permanently change a list after user's input? Ablazesphere 6 4,339 Oct-31-2018, 08:30 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020