Reputation: 167
I am trying to create a guessing game for myself. I want to have the computer have a random number which I have to guess. Based on what I guess, it would then respond with "higher or lower" and this should keep happening before i get the right number however what has happened is that now when I put in a guess, it says higher or lower and just repeats this throughout the page. How do I end this loop and make sure that after each "higher" or "lower" i just get another change. Please find code below.
import random
the_number = random.randrange(100)+ 1
guess= int(raw_input("Take a guess: "))
tries = 1
while (guess != the_number):
if (guess > the_number):
print "Lower..."
break
elif (guess<the_number):
print " Higher..."
break
elif (guess == the_number):
print "Awesome achievement"
break
else:
print "Better luck next time."
guess = int(raw_input("Take another guess "))
Upvotes: 0
Views: 147
Reputation: 107
something like this
import random
def main():
secret = random.randint(1, 10)
while (guess != secret):
guess = int(raw_input("Guess a number between 1 and 10: "))
if guess > secret:
print "too high."
elif guess < secret:
print "too low."
elif guess <1 or guess > 10:
print "invalid guess."
elif guess == secret:
print "You win"
break
Upvotes: 0
Reputation: 83255
import random
the_number = random.randrange(100) + 1
tries = 0
while True:
tries += 1
guess = int(raw_input("Take a guess: "))
if guess > the_number:
print "Lower..."
elif guess < the_number:
print " Higher..."
else:
print "Awesome achievement, it took you", tries, "tries"
break
Upvotes: 2