import random
number = random.randrange(1, 10)
print(number)
guess_count = 0
guess_limit = 3
out_of_gusses = False
guess = int(input("enter ur guess: "))
while guess > number or guess != number and not out_of_gusses:
if guess > number:
print("ur guess is higer than the number")
else:
print("ur guess is lower than the number:")
if guess_count < guess_limit:
guess = int(input("enter ur guess: "))
guess_count += 1
else:
out_of_gusses = True
if out_of_gusses:
print("Out of guesses u lose: ")
else:
print("u Win")
my problem is that when i run the program and i did enter my number it says u win
even though the number is wrong and i also get 4 tries when the limit is set to 3 guess:limit = 3
iam new at coding so iam not to sure what the problem is but i think its somthing with the condintion of my while loop but cant quite get my head around how i should phase then
Here's how you can restructure your entire logic into something simple that works:
import random
number = random.randrange(1, 10)
print(number)
guess_count = 0
guess_limit = 3
while True:
if guess_count < guess_limit:
guess = int(input("enter ur guess: "))
guess_count += 1
if guess == number:
print("u Win")
break
else:
print("Out of guesses u lose: ")
break
if guess > number:
print("ur guess is higer than the number")
elif guess < number:
print("ur guess is lower than the number:")
Basically, you create an infinite loop that you break out of, if the guess is correct or if they have run out of guesses. This way, you can have your entire dice game logic into that while
loop.
There are a few flaws in your code
while guess > number or guess != number and not out_of_gusses:
This resolves to
while guess != number and not out_of_gusses:
because whenever guess > number
is true
, guess != number
is anyway true
. That also means that if your guess is correct in the first place, the while loop is not executed at all.
The problem with your off by one guess_count
comes from the fact that you're initializing guess_count
with 0 ignoring the initial guess.
if out_of_gusses:
print("Out of guesses u lose: ")
else:
print("u Win")
This conclusion is not correct, just because you're not out of guesses doesn't mean you won!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.