I'm having trouble with getting the while loop to function correctly in my code.
I want to create a program that randomly generates 2 numbers and asks the user to give the sum of them. This is what I have so far:
import random
def add_random_numbers():
num1 = random.randint(0, 100)
num2 = random.randint(0, 100)
print(num1, ' ', num2)
answer = num1 num2
user_answer = int(input("Enter Your Answer: "))
while user_answer != answer:
if (user_answer > answer):
print("Sorry, your guess is too high.")
int(input("\nTry again: "))
if (user_answer < answer):
print("Sorry, your guess is too low.")
int(input("\nTry again: "))
add_random_numbers()
But once you enter the wrong number and you're prompted to try again, the while loop no longer works. It just keeps repeating the first result. I know it's probably a simple fix but I can't figure it out. What am I missing?
CodePudding user response:
You need to reassign your input back to user_answer
while user_answer != answer:
if (user_answer > answer):
print("Sorry, your guess is too high.")
user_answer = int(input("\nTry again: "))
if (user_answer < answer):
print("Sorry, your guess is too low.")
User_answer = int(input("\nTry again: "))
CodePudding user response:
That's because you don't reassing user_answer
on your input "Try again". So that's why it keeps using the first input
CodePudding user response:
So the problem lies in the line where you ask the user to put a new input
int(input("\nTry again: "))
This line does ask for a new input but the answer isn't assigned anywhere, in order to fix this you only need to rewrite the value of user_answer as follows
user_answer = int(input("\nTry again: "))