Reputation: 71
I am running the following code and it loops through it with an output, but then goes to the 'elif' statement skipping the if statement the first time through. After the second time through, even if I give it the wrong answer, it stops. How can I get it to repeat with a new set of random numbers for an incorrect guess, but then accept it if it is correct?
from random import randint
def solve():
a = randint(0,10)
b = randint(0,10)
total = a + b
print(str(a) + ' + ' + str(b) + ' =')
guess = input()
if (guess == total):
print("Correct")
elif (guess != total):
print('Try again')
a = randint(0,10)
b = randint(0,10)
total = a + b
print(str(a) + ' + ' + str(b) + ' =')
guess = input()
solve()
Upvotes: 0
Views: 80
Reputation: 1203
You can use an infinite while loop(while loop with a condition which always evaluates as True). eg.
while True:
# Do something
Also, break the flow using break
keyword whenever after it meets the required condition.
while True:
# code
if condition:
break
Upvotes: 0
Reputation: 411
input()
always returns a string. if you want to compare input to a number, you have to convert input to an integer.
instead ofguess = input()
, you should useguess = int(input())
that's why your code skips the if
statement, string will never be equal to int.
Upvotes: -1
Reputation: 34016
Input returns a string it would never be equal to an integer
def solve():
a = randint(0, 10)
b = randint(0, 10)
total = a + b
print(str(a) + ' + ' + str(b) + ' =')
guess = int(input())
if (guess == total):
print("Correct")
elif (guess != total):
print('Try again')
a = randint(0, 10)
b = randint(0, 10)
total = a + b
print(str(a) + ' + ' + str(b) + ' =')
guess = int(input())
solve()
Your final code should be something like:
def solve():
while True:
a = randint(0, 10)
b = randint(0, 10)
total = a + b
print(str(a) + ' + ' + str(b) + ' =')
guess = int((input()))
if guess == total:
print("Correct")
break
print('Try again')
Upvotes: 2