Home > database >  How can I debug an if statement that isn't working?
How can I debug an if statement that isn't working?

Time:12-15

I do not know what I did wrong.

def main():  # store anything to then replay code.
    import time

    math = int(input("Hi there, what is 32   16? =")) # asking what 32 16 is.

    if math == "48":
      print("Correct!") #this is the if statement that isn't working, suppose to say correct if the input is 48.

    else:
      print("Not quite..")  # this would come up instead of 'correct' if I would put 48.


    time.sleep(2)  # a delay
    restart=input('Do you wish to start again? ').lower()
    if restart == 'yes':  # if the player wants to play the game again.
      main()  # to replay code.

    else:
      exit()  # this wouldn't start the game again.


 main()  # this just starts main.

CodePudding user response:

Change this

if math == "48":

to this:

if math == 48:

You convert the input to int already.

CodePudding user response:

Wouldn't this be better served in a while loop as opposed to being enumerated at runtime?

To answer your question, you've already declared an integer, the quotes make python interpret it as a string.

CodePudding user response:

You were super close but there are a few things that needed tweaking to get it working.

First, you will need to make sure that your main is defined correctly and remove the "**" from your code before the comments.

Second, the reason your code always fails the if statement check for if they got the correct answer is that you are casting the answer to an integer when you get the input, but then comparing it to a string version of 48, deleting the quotations around that should fix the issue as well.

I have implemented these and had the code working in python3 on my system.

Hope this helps (modified code below)

import time

def main():
  math = int(input("Hi there, what is 32   16? =")) #

  if math == 48:
    print("Correct!") #This is where I made the change, removing the 
                       quotes that surrounded the 48. 

  else:
    print("Not quite..")#this would come up instead of 'correct' if I 
                         would put 48.**


  time.sleep(2)#a delay**
  restart=input('Do you wish to start again? ').lower()
  if restart == 'yes':#if the player wants to play the game again.**
    main()#to replay code.**

  else:
    exit()#this wouldn't start the game again.**


main()#this just starts main.**
  • Related