0

Let me start by saying it loud: this is not homework, mandatory assignment or anything with a deadline. I'm doing this for my own practice. With that said, I really appriciate your help!

I'm working on a dynamic, text based (for now), Test Maker program. The user gets to write the question, choose how many answers it will have, what score to give for it, choose the right question and print the results in a table form.

How can I write a for loop so I can go through the lists and print the output according to the table?

Thanks again for your time!

I know there's a limit to the code size but I really don't know what can be skipped in this one so i'm truely sorry in advance and will edit it if someone will advise me what to remove.

this is the result table template: Result Table Template

this is the function where I want to add the for loop:

def finish(lines):
    
        print("\n\n==============RESULTS==============\n")
        print("#\t Question\t Answer\t\t Score")
        number_of_questions = len(question_list)

code:

def get_questions():

    question = input("Enter your question: ")
    if len(question) == 0:
        print("No Empty Questions.")
        get_questions()

    question_list.append(question)

    return question


def get_question_score(s):

    try:
        s = int(input("Enter Question Score: "))

    except ValueError:
        print("[!]Error! Use numbers.")

    return s


def check_sum(s):

    scores_local.clear()

    try:
        if sum(scores) + s > 100:
            print("Score sum is higher than 100")
            print(f"{100 - sum(scores)} left")
            score = 0
            if len(scores) != 0:
                scores.pop()
            return False

    except ValueError:
        print("Use Numbers.")

    scores_local.append(s)
    scores.append(s)

    return True


def get_number_of_answers(n_o_a):

    try:
        n_o_a = int(input("Number of answers (Max 4)? "))

    except ValueError:
        print("Please select [2-4]")

    number_of_answers.append(n_o_a)

    return n_o_a


def big_small(n_o_a):

    if n_o_a < 2 or n_o_a > 4:
        print("Please select [2-4]")
        answers.clear()
        answers_local.clear()
        big_small(n_o_a=number_of_answers[0])
        return False

    elif 2 > number_of_answers[0] > 4:
        print("Error! Please select [2-4]")
        return False

    else:
        print(n_o_a)
        return True


def get_answers(num_of_answers, answer):

    answers_local.clear()
    answers.clear()

    for ans in range(number_of_answers[0]):
        answer = input(f"Answer #{ans+1}: ")    # Start indexing from 1
        if len(answer) == 0:
            print("Error! No Input!")
            get_answers(num_of_answers, answer="")

        answers_local.append(answer)
        answers.append(answer)

    return answer


def get_right_answer_number(num):

    try:
        num = int(input("Type the Right Answer Number: "))

    except ValueError:
        print("Error! Please type numbers only.")

    return num


def check_right_answer_number(num):

    if 0 < num <= number_of_answers[0]:
        return True

    else:
        return False


def ask_if_sure(ans):   # Returns True

    ask_sure = input("Are you sure? [Y/n]: ")
    if ask_sure.lower() == "n":
        number_of_answers.clear()
        check_right_answer_number(num=number_of_answers[0])

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

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


def ask_continue():

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

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

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


def restart():

    answers_local.clear()
    number_of_answers.clear()
    right_answer_number.clear()
    main()


def finish(lines):

    print("\n\n==============RESULTS==============\n")
    print("#\t Question\t Answer\t\t Score")
    number_of_questions = len(question_list)


def main():

    questions = get_questions()
    question_score = get_question_score(s=0)
    score_sum = check_sum(question_score)   # Returns True/False
    num_of_answers = get_number_of_answers(n_o_a=0)
    is_bigger = big_small(num_of_answers)   # Returns True/False

    if not is_bigger:
        print(f"Question score: {question_score}, Valid: {score_sum}")
        if sum(scores) != 0:
            scores.pop()
            question_score = get_question_score(s=0)

    while is_bigger:

        question = questions[-1]
        multiple_answers = get_answers(num_of_answers, answer="")
        print(answers_local)
        right_answer_number_var = get_right_answer_number(num=0)
        print(right_answer_number_var)
        is_right = check_right_answer_number(right_answer_number_var)

        if not is_right:
            print(f"Error! Please select [1={number_of_answers[0]}")
            right_answer_number_var = get_right_answer_number(num=0)

        while is_right:
            sure = ask_if_sure(ans="")

            while sure:
                if number_of_answers[0] < len(questions):
                    lines = len(questions)
                else:
                    lines = number_of_answers[0]

                answers.append(right_answer_number_var)
                ask_if_continue = ask_continue()
                if not ask_if_continue:
                    finish(lines)

                while ask_if_continue:
                    restart()
                    break
                break
            break
        break


if __name__ == "__main__":

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

    main()

1 Answers1

0

So thanks to @maddy I was able to understand the FOR loop more deeply and managed to fix it with this piece of code:

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]}")

This works fine for me as it is because the future version will be converted to GUI.

here's the full code if you want to review it:

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)

There are some more bugs in it but they have nothing to do with the answer.

Thanks @maddy!