0

I am trying to input a try/except into this code for people inputting letters, not numbers

My code:



def quiz():
  while True:
    score = 0 
    for questions in Quiz_qs:
      print("\n" + i[0])
          if guess == i[1]:
          print("Correct!")
          score +=  1
          print(score, "out of 10”)
        else:
          print("\nincorrect!")
          print(score, "out of 10”)
          break
      

Quiz()
  • 1
    Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Show where the intermediate results differ from what you expected. We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. You posted 80 lines of code for a problem of 10-15 lines. – Prune Nov 19 '20 at 18:42
  • Where is the code that is supposed to throw the `ValueError` you say you expect? All I see is code that takes *any* guess and compares it to the desired answer. You haven't done any explicit or implicit input validation. – Prune Nov 19 '20 at 18:43
  • That is closer to the solution; please edit that into your question as you reduce this to a MRE. The looping problem is that you handle the error outside of any appropriate loop. This is now reduced to a [duplicate request](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Prune Nov 19 '20 at 19:33

3 Answers3

0

I'm a beginner too, but maybe I can help you and also learn something too. I think the problem is that you are not asking to have a int answer in the try. With the 'if' statement you are only considering the right answer, so the 'else' includes every other single answer that is not the right one, also the char ones. You should put another condition to check if answer is a number or not and call except if it isn't.

Hope I helped.

0

Change your code as follows:

G_statements = [["What is 5+5?", "10"]]
G_statements.append(["What is the square root of 9?", "3"])
G_statements.append(["What is 30 / 3", "10"])
G_statements.append(["What is 24 x 2", "48"])
G_statements.append(["What is 40 / 5", "8"])
G_statements.append(["What is 150 - 45", "105"])
G_statements.append(["What is 9x9", "81"])
G_statements.append(["What is 25+5", "30"])


def Generalquiz():
    score = 0
    for i in G_statements:
        print("\n" + i[0])
        while True:
            try:
                guess = int(input("\nAnswer:"))
                break
            except ValueError:
                print("Characters not accepted, Please enter a number")
            
        if guess == int(i[1]):
            print("Correct!")
            score = score + 1
            print(score, "out of 8")
            print("\n")
        else:
            print("\nincorrect!")
            print(score, "out of 8")
            print("\n")



Generalquiz()
0
G_statements = [["What is 5+5?", "10"],
                ["What is the square root of 9?", "3"],
                ["What is 30 / 3", "10"],
                ["What is 24 x 2", "48"],
                ["What is 40 / 5", "8"],
                ["What is 150 - 45", "105"],
                ["What is 9x9", "81"],
                ["What is 25+5", "30"]]

# python lists support multi type variables as such ["What is 25+5", 30]
# if you declare the list this way, you can simply do 'if guess == i[1]'

def Generalquiz():
    score = 0
    # ask a question
    for i in G_statements:
        print("\n" + i[0])

        # try to get a valid (not necessarily correct) answer
        while True: # keep asking for a valid input
            try: # TRY receiving a valid input
                guess = int(input("\nAnswer:")) # try to CAST input to INT, if successful, the input was int, otherwise raise a ValueError
                break
            except ValueError:
                print("Characters not accepted, Please enter a number")
                continue # as long as we have an error (that is the input wasn't an int) CONTINUE asking for a valid input

        # logic part   
        if guess == int(i[1]): # correct answer is a string (not the best way, see above comment), convert it to int
            score+=1
            print("Correct!", score, "out of ", len(G_statements)) # LENgth of G_statements, avoid constant values if possible
        else: print("\n\nincorrect!", score, "out of 8\n")

comments should be sufficient for explanation, if you just started to code, try to break the problem into smaller chunks and solve them separately, best of luck!

Leon Rai
  • 1,401
  • 3
  • 9
  • 15