This is a guessing game, the variable ans here become type str at the while loop and cause an error. TypeError: '<' not supported between instances of 'str' and 'int'. Why is ans a str
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = input(f"Guess between 1 and {x}: ")
chance = 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)
CodePudding user response:
At first indeed you initialize it with 0, but it overlapped with the input()
inside the loop thats returns a string, so the initialization doesn't mean anything. To solve it you have to cast the input to integer
import random
def guess(x):
ansnum = random.randint(1,x)
ans = 0
chance = 0
limit = 4
while ans!= ansnum and chance < limit :
ans = int(input(f"Guess between 1 and {x}: "))
chance = 1
if ans < ansnum:
print("close,too low")
else:
print ("close,too high")
else:
print("You Guess IT")
guess(10)