Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So i'm new to programming and I was trying to make a 'guess the number' program but it stops after 3 wrong guesses. I'm probably doing something really stupid so sorry if the question sounds dumb.
Thanks in advance
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
while guess > number:
print('Lower')
guess = int(input('Try again: '))
while guess < number:
print('Higher')
guess = int(input('Try again: '))
By having the three cases (equal, more than, less than) handled in separated blocks, once you get past one, you don't come back to it. For instance, the program checks for equality only once, and if it fails the first time, then it never checks again. You should put all three in one block.
from random import *
number = randrange(1,100)
max_attempts = 100
for attempt in range(max_attempts):
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
break
if guess > number:
print('Lower')
continue
if guess < number
print('Higher')
continue
break means to stop the loop, and continue means to go on to the next iteration of the loop. I used a for-loop since that is guaranteed to halt.
As soon as you break out of a while loop, you can not revisit that loop again. I.E for while guess > number, as soon as the user guesses a number that is <= number then you will break out the loop and the program will move past it.
Instead use this code:
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while guess != number:
if guess < number:
print('Higher')
else:
print('Lower')
guess = int(input('Try again: '))
print('Well done!')
This program runs the while loop when guess != number. This condition will break when guess != number is False, or in other words, when the user guesses the correct number.
You need to change the while loops to this:
while guess != number:
if guess > number:
print('Higher')
guess = int(input('Try again: '))
elif guess < number:
print('Lower')
guess = int(input('Try again: '))
Basically, previously, if the guess is smaller that the number, it starts the while loop, while guess < number However, when the guess is bigger, the while loop stops because the guess is no longer smaller than the number.
To fix this, create one while loop and, in that, check to see in the guess is bigger or smaller than the number.
You could therefore, remove the guess from each if statement, and put it at the end of the while loop, if that makes sense, like this:
while guess != number:
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
guess = int(input('Try again: ')
Using multiple while loops makes your debugging more complicated without any gain.
I would suggest you to use a single while loop:
from random import *
number = randrange(1,100)
guessed = False
while not guessed:
guess = int(input('Guess the number (between 1-100)'))
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
else:
print('Well done!')
guessed = True
I'm not very much of a programmer neither but I Have been using python regularly lately , although i'm not sure what causes this problem , you can try this alternative code that worked pretty well for me :
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while True:
if guess > number:
print('Lower')
guess = int(input('Try again: '))
elif guess < number:
print('Higher')
guess = int(input('Try again: '))
else:
print('Well done!')
break
Related
import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')
I was making this simple python game where you guess a random number. I was wondering how you would loop it so it would keep going until you get the correct number. It needs to do that without changing the number while the player is guessing.
import random
print('Welcome to Guess The Number V1.0')
print('the rules are simple guess a number 1-6 and see if youre correct')
number = random.randint(0,7)
#------------------------------------------------------
guess = int(input('Enter a number:'))
print(guess)
#------------------------------------------------------
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
#-------------------------------------------------------
if guess == number:
print('Correct!')
If you used a while loop you could make it run without needing to stop it and reload the site. it would look like this
while guess != number:
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
#-------------------------------------------------------
if guess == number:
print('Correct!')
You would use a while loop to repeat the guessing procedure like so:
import random
print('Welcome to Guess The Number V1.0')
print('the rules are simple guess a number 1-6 and see if youre correct')
number = random.randint(0,7)
#------------------------------------------------------
guess = int(input('Enter a number:'))
while guess != number: #Following code only runs if the guess isn't correct
if guess > number:
print('Your guess was to high')
if guess < number:
print('Your guess was to low')
guess = int(input('Enter a number:')) #Need this here to ask for another guess
#and avoid an infinite loop
print('Correct!')
Hope that helps!
Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.
I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess.
import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.
I've fixed your code for you. Try this:
import random
x = random.randint(1, 100)
while True:
try:
guess = int(raw_input("Guess the number: "))
except ValueError:
print("Not a valid number, try again!")
continue
if guess < x:
print("Too low, guess again")
elif guess > x:
print("Too high, guess again")
elif x == guess:
print ("That is correct!")
break
You don't need to prompt the user for input after every guess, that's what the first input prompt is for. Because we are specifying while True, the user will get prompted to input a number every single time unless they enter the correct number, which in that case, we break the infinite loop.
Additionally, we can put the input statement in a try block, because we are casting the input as an integer right there. If the user enters a string, the program would otherwise fail if it tried to cast it as an integer, but if we except ValueError: and then continue, we will alert the user that their input is invalid, and then prompt them for input once again.
Your if statements are all independent:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
The second and third if statements will always test guess again, even if the first if test matched. And if the first if test matched and you entered a non-numeric guess value, those two tests will fail as the int() call will throw a ValueError exception.
You could tell Python that the tests are interdependent by using elif and else; now Python will only execute the first matching block, and skip the others entirely:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
elif x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
else:
print ("That is correct!")
break
This means that execution continuous after the else block when either the if or elif tests matched.
Note that I used else at the end; if the number is neither too high nor too low, the number must be equal, there is no other option. There is no need to test for that explicitly.
You are now repeating yourself however. You are asking for a guess in 3 different places. You could ask once and let the loop take care of asking for a new value:
while True:
while True:
guess = input("Guess the number:")
if guess.isnumeric():
break
print("Not a valid number, try again!")
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
That's a lot less repetition already; a separate while loop asks for a number until it is actually numeric, and guess is converted to int() just once.
You could remove that nested while True: and just use the outer one here, the result would be the same, provided you use the continue keyword to skip the rest of the loop when you don't have a numeric value:
while True:
guess = input("Guess the number:")
if not guess.isnumeric():
print("Not a valid number, try again!")
continue # skip to the top of the loop again, so ask again
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
You need to surround your guessing logic in another loop that continues until the guess is correct.
pseudocode:
choose_target_answer
while player_has_not_guessed_answer
get_player_guess
if player_guess_is_valid
respond_to_player_guess
else
give_error_message
This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!
for lp in range(100):
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
This is some basic code that I was told to make for a basic computing class. My aim is to make a simple 'game' where the user has to guess a random number that the computer has picked (1-100) This is a small section of the code where I want to continue checking if the guess is equal to, lower or higher than the number; but if I put a print statement below, it will print the text 100 times. How can I remove this problem?
Thanks in advance.
It seems like you're omitting the guessing stage. Where is the program asking the user for input?
Ask them at the beginning of the loop!
for lp in range(100):
guess = int(input('Guess number {0}:'.format(lp + 1)))
...
You need to get a new input each time through your loop; otherwise you just keep checking the same things.
for lp in range(100):
if guess == number:
break
if guess < number:
# Get a new guess!
guess = int(raw_input("Nah m8, Higher."))
else:
# Get a new guess!
guess = int(raw_input("Nah m8, lower."))
You should ask for a guess inside the loop:
while True:
guess = int(raw_input("Guess: "))
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
import random
number = 0
x = []
while number < 100:
guess = random.randint(1,100)
if number < guess:
print(f 'Number {number} is less than guess {guess}')
elif number > guess:
print(f 'Number {number} is greater than guess {guess}')
number += 1
This will work for you