0

So I'm making a math game where the user gets three tries to answer the problem and if not it shows the answer and goes to the next question however my code only lets they get it wrong once before going to the next problem. What am I doing wrong

    nQuestions = 0
    cAnswers = 0
    attempts = 0
    lvl = get_level()
    while nQuestions != 10:
        if attempts == 0:
            x, y = generate_integer(lvl)
            answer = x + y
            sum = int(input(f"{x} + {y} = "))
        if sum == answer:
                cAnswers += 1 
                attempts = 0
                nQuestions +=1
                continue
        else:
                attempts += 1
                if attempts == 3:
                    print(f"{x} + {y} = {answer}")
                    attempts = 0
                    nQuestions += 1
                continue
Big_Port
  • 91
  • 9
  • "if attempts == 0" looks like it would only trigger once. If you want 3 attempts it should be "if attempts <= 3:" but it's also redundant if you are handling it in the else portion. You could remove the first if altogether. – mr_mooo_cow Jul 20 '23 at 16:22
  • 2
    because you only give them a chance to enter input when `if attempts == 0:`. you want to un-indent the line `sum = int(input(f"{x} + {y} = "))` so that it is outside of that if block, so that it executes each time through the while loop – Anentropic Jul 20 '23 at 16:23

1 Answers1

0

It is because your code let's the user input only once. While the number of attempts is less than 3, you should have asked the user to input again (retry).

The following works:

nQuestions = 0
cAnswers = 0
lvl = get_level()
while nQuestions < 10:
    x, y = generate_integer(lvl)
    answer = x + y
    #sum = int(input(f"{x} + {y} = "))
    attempts = 0
    while attempts<3:
        sum = int(input(f"{x} + {y} = "))
        if sum == answer:
            cAnswers += 1
            nQuestions +=1
            break
        else:
            attempts += 1
    if attempts == 3:
            print(f"{x} + {y} = {answer}")
            nQuestions += 1
Niveditha S
  • 186
  • 7
  • 1
    Note: Thanks to how [Python allows `else` to chain to `while` and `for` loops](https://stackoverflow.com/q/3295938/364696), you could replace `if attempts == 3:` with just `else:`. The `else:` block will execute if the `while` exits without a `break`, and will be skipped if it exits due to a `break` (or `return`, or thrown exception). – ShadowRanger Jul 20 '23 at 17:03