Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

closed If statement in Python doesn't function properly...

+3 votes
asked Feb 24, 2023 by YC72909 (340 points)
closed Feb 25, 2023 by Admin

Hello,

I have an "if" statement that isn't functioning properly in my Python code. It doesn't give me an error code, but when it executes, it doesn't do what the code says. Here is the code. Do you see any problem? Thank you for your help.

if play == 1:
    question = random.choice(q_num)
    question2 = random.choice(q_num2)
    print(" ")
    print("What is", question, "*", question2, "?")
    print(" ")
    playerans = input("")
    print(" ")
    answer = question * question2
if not playerans == answer:
    print("Sorry, incorrect...")
    print("Click 'Run' to play again.")
    exit()
else:
    print("Correct!")
    

YC72909 Scratch and Online GDB

closed with the note: answered

2 Answers

0 votes
answered Feb 24, 2023 by Peter Minarik (87,810 points)

I suppose this is because the type of the variables playerans and answer do not match. The type of (the expected) answer is probably a number, while playerans is a string. You cannot compare a string to a number.

Turn your playerans to a number as well:

playerans = int(input(f"{question} * {question2} = "))
commented Feb 24, 2023 by YC72909 (340 points)
Thank you both, it worked!
0 votes
answered Feb 24, 2023 by Eidnoxon (5,160 points)

playerans = int(input(""))

The "int" keyword is important, because otherwise, the program will read the player's answer as string. And as you can tell, you can't add 2 numbers in string together, because the result would be stupid. The "int" keyword transforms the string to an integer.

And if you use

print(f"What is {str(question)} * {str(question2)} ?")

instead of print("What is", question, "*", question2, "?"); would make your code more readable. This was just a small thing.

You see, back to the playerans = int(input("")) the "int" keyword is not for only transform string to integer in your code. In your code, the "int" keyword makes your if statement work. You typed:

if playerans == answer:

Here, you are comparing strings to integers, which is illegal in every programming language. That's why you have to transform your string to an integer.

It might've been a little too long, but look, I tried to explain everything. Good luck on your coding journey! :D

commented Feb 24, 2023 by YC72909 (340 points)
Thank you, it worked!
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...