import random
def guess_number():
numb = random.randrange (10) +1
guessestaken = 0
guess = input("whats your number")
while (guess != numb):
if (guess > numb):
print "too low"
elif(guess < numb):
print "too high"
else:
input("whats your next numb")
tries += 1
I am making a number guessing game with range 1 to 10 and I need help on getting the loop to stop. when I guess the number it keeps going
Here's a working example of what you're trying to do:
import random
guessesTaken = 0
number = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.\n')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You never reassign guess within the loop, so the truth value of guess != numb never changes. Put guess = before the input() call within the loop, or restructure it to a while True: ... break layout. Also, you only give the user another chance to guess the number if they get it exactly correct. Read through your code slowly and try to follow along with what the interpreter is doing.
Related
Just starting out here and was hoping someone could help me with an issue I'm having. Haven't been able to find any clear answers online, likely because this is such an early level exercise.
Basically I want to have the program print a different response after the first incorrect answer. For example... the first prompt is "Take a guess!" but after that I would like it to say... "Take another guess!"
Could anyone shed some light on this for me? Thanks in advance.
# Number guessing game.
import random
from time import sleep
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20. You have five chances to guess correctly.')
sleep(1)
# Ask the player to guess six times.
for guessesTaken in range(1, 6):
print('Take a guess!')
if guessesTaken > 1:
print('Take another guess!')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break #this is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber) + '.')
Instead of using print to show the prompt, add it to the input function call. Within that you can use a ternary-style expression. Here's an example:
import random
NGUESSES = 6
RANGE = 1, 20
computer = random.randint(*RANGE)
for guess in range(NGUESSES):
if (user := int(input('Take a guess: ' if guess == 0 else 'Try again: '))) == computer:
print(f'Good job! You guessed correctly in {guess+1} guesses')
break
print('Too low' if user < computer else 'Too high')
else:
print(f'Nope. The number I was thinking of was {computer}')
I am on chapter three of Automate The Boring Stuff with Python. For exercise guessTheNumber.py I am unclear as to how "guessesTaken" was defined and how it is being incremented.
https://automatetheboringstuff.com/chapter3/
How is this program:
1. Defining the guessesTaken variable
2. increasing the value of guessesTaken for each guess
Thank you,
# This is a guess the number game.
import random
secretNumber = random.randint(1, 20)
print('I am thinking of a number between 1 and 20.')
# Ask the player to guess 6 times.
for guessesTaken in range(1, 7):
print('Take a guess.')
guess = int(input())
if guess < secretNumber:
print('Your guess is too low.')
elif guess > secretNumber:
print('Your guess is too high.')
else:
break # this condition is the correct guess!
if guess == secretNumber:
print('Good job! You guessed my number in ' + str(guessesTaken) +' guesses!')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
It is used as a loop counter, it was defined in:
for guessesTaken in range(1, 7):
And is being incremented in every iteration of the for loop. So if the loop counter reaches 3, that means the loop ran (didn't break) three times, and so the user had to guess three times.
The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.
I'm new to python and I'm trying to make a simple Guess the number game, and I'm stuck in an if statement in a while loop. here is the code.
I'm experiencing it at the Your guess it too high and the low one. I tried breaking it, but it simply stops the whole things
def guess_the_number():
number = random.randrange(20)
guessesMade = 0
print('Take a guess')
guess = input()
guess = int(guess)
while guessesMade < 6:
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
print'You got it in', guessesMade, 'guess(es)! Congratulaions!'
else:
print'I\'m sorry, the number was', number
You never increment guessesMade so guessesMade < 6 will always be True. You need to modify this value within your loop. You also need to move your prompt for user input into the loop
while guessesMade < 6:
guess = int(input('Take a guess'))
if guess < number:
print('Your guess is too low.')
guessesMade += 1
elif guess > number:
print('Your guess is too high.')
guessesMade += 1
else:
break
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have to make an accumulator that counts the number of entries a user uses to guess a random number. I have all the while statements figured out but I can't get the piece that counts how many entries it took. Thanks for any help!
import random
secretNumber = random.randint(1,100)
secretNumber = int(secretNumber)
print("Guess a number between 1 and 100!")
number = input("Your guess: ")
number = int(number)
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
number = input("Your guess: ")
number = int(number)
if number < secretNumber:
print("Too low!")
number = input("Your guess: ")
number = int(number)
while number == secretNumber:
print("You got it in",tries,"tries")
break
the part I need help with is implementing the tries accumulator after the break
The first thing you want to ask is when you print tries, what are you getting?
Effectively, you will see you are always getting 1.
Because, you didn't increment. You didn't add as user keeps guessing.
Generally, you can write tries = tries + 1 for each guess.
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
if number < secretNumber:
print("Too low!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
while number == secretNumber:
print("You got it in",tries,"tries")
break
This code still has some problem. The 2nd loop doesn't make sense. A loop sounds like loop. It keeps running until a condition is met or someone (you) interrupts it and tells it to exit.
If user found the number, then while number !- secretNumber will become False right?
It will exit the first loop. Hence, you can skip the second loop and congratulate the user.
Another minor thing is the double if statements.
if statements are expensive. Computer has to test to guess right. But either way, there is a different way to do multiple conditions.
if condition1 met:
do this
elif condition2 met:
do this
elif condition3 met:
do this
elif more....
else: # optional, but encourage, this is a default fallback case
do this
If number > secretNumber is True, then you don't need to test number < secretNumber in theory. It makes the code cleaner and logically sound by adapting if .. elif .. else
import random
secretNumber = random.randint(1,100)
secretNumber = int(secretNumber)
print("Guess a number between 1 and 100!")
number = input("Your guess: ")
number = int(number)
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
elif number < secretNumber:
print("Too low!")
tries = tries + 1 # here is the addition
number = input("Your guess: ")
number = int(number)
print("You got it in",tries,"tries")
# another way to print is
# print("You got it in %s tries" % tries)
# print("You got it in {t} tries".format(t=tries))
For beginners, use print to help debug your code.
Just put the line
tries += 1
in the loop- this line increases the tries variable by 1.
I also took the liberty of shortening it by removing part of it from the if statement, and removed the second while loop (since the loop always occurs exactly once there's no reason to put a loop there):
while number != secretNumber:
tries += 1
if number > secretNumber:
print("Too high!")
if number < secretNumber:
print("Too low!")
number = input("Your guess: ")
number = int(number)
print("You got it in",tries,"tries")
you can just add to the number of tries if you get it wrong:
...
while number != secretNumber:
tries += 1
if number > secretNumber:
print("Too high!")
...
Also, at the end instead of this:
while number == secretNumber:
print("You got it in",tries,"tries")
break
you can just use this:
print("You got it in",tries,"tries")
because it would only get to this point if you get the number right.
Another thing, tries should initially be equal to 0, no one, because at the beginning you tried 0 times, not 1.
import random
i = 0
rand_num = random.randint(1, 100)
while True:
i += 1
try:
guess = int(input('Guess the number: ')
except ValueError:
print('Invalid input, try again')
continue
if guess < rand_num:
print('Too low, try again')
elif guess > rand_num:
print('Too high, try again')
else:
print('You got it in ', tries, ' tries!')
break
You want to add the extra line tries += 1 in the while loop. What this does is add 1 to tries every guess. So then your code would be:
import random
secretNumber = random.randint(1,100)
secretNumber = int(secretNumber)
print("Guess a number between 1 and 100!")
number = input("Your guess: ")
number = int(number)
tries = 1
while number != secretNumber:
if number > secretNumber:
print("Too high!")
number = input("Your guess: ")
number = int(number)
if number < secretNumber:
print("Too low!")
number = input("Your guess: ")
number = int(number)
while number == secretNumber:
print("You got it in",tries,"tries")
break