2

Created a little program that generates two values between 1 and 10 (inclusive), and prompts the user to find the sum as an answer.

I'm trying to use a while loop here. It seems that the code "while (numb1 + numb2 != answer)" will always evaluate to true (even when false), and so the loop never exits.

Wondering what I might have missed? Would appreciate any input!

import random
numb1 = random.randint(1,10)
numb2 = random.randint(1,10)

print('What is: ', numb1, ' + ', numb2, '?')
answer = input('Answer: ')

while (numb1 + numb2 != answer):
    print('Incorrect, try again!')
    answer = input('Answer: ')
print('Correct!')
2
  • 1
    input returns a string, but numb1 and numb2 are integers. Cast to an int before comparing: answer = int(input('Answer: ')) Commented Mar 13, 2018 at 19:26
  • That's it, thanks! I thought "input" was for integers and "raw_input" was for strings. Guess I misunderstood this. Thank you. Commented Mar 13, 2018 at 19:50

2 Answers 2

7

answer is a str while numb1 and numb2 are ints.

>>> 1 == "1"
False

Do this:

while numb1 + numb2 != int(answer):
Sign up to request clarification or add additional context in comments.

Comments

0

Because you comparing int values with str values, which cannot be equal in any case.

Before comparison convert answer to int with

answer = int(input('Answer: '))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.