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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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__ ....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 2,013 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  functional LEDs in an array or list? // RPi user Doczu 5 2,835 Aug-23-2022, 05:37 PM
Last Post: Yoriz
  User-defined function to reset variables? Mark17 3 3,294 May-25-2022, 07:22 PM
Last Post: Gribouillis
  Looking for a way to loop until user enters from a list? PythonW19 7 4,665 Mar-21-2021, 08:56 PM
Last Post: PythonW19
  User input/picking from a list AnunnakiKungFu 2 2,966 Feb-27-2021, 12:10 AM
Last Post: BashBedlam
  How to reset row value in pandas Mekala 0 1,995 Sep-19-2020, 09:36 AM
Last Post: Mekala
  cannot reset list in for loop bstanard 3 4,901 Feb-28-2020, 01:24 AM
Last Post: jefsummers
  Help with calling list from user input farispython 5 4,000 Nov-03-2019, 03:13 PM
Last Post: Gribouillis
  Creating csv header from user-input list dvanommen 2 2,852 Aug-26-2019, 08:51 PM
Last Post: dvanommen
  Reset a variable mln4python 4 10,440 Aug-19-2019, 08:28 AM
Last Post: mln4python

Forum Jump:

User Panel Messages

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