I'm writing the radius guessing game and stumbled into the looping problem.
It might seem like a silly question but is the break placing right? or should it be something else?
import random
import math
number = random.randint(1, 20)
area = math.pi * number**2
guessesTaken = 0
print '%.0f is the area' % (area)
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
while guessesTaken < 6:
if guess < number:
print('Your guess is too low.')
if(guess > number):
print('Your guess is too high.')
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job! You guessed my number in ' + guessesTaken + ' guesses!')
break
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You should place the last two ifs outside the while loop. Moreover, inside the while you should re-ask for input if the user guessed incorrectly, otherwise guesses never changes and you'd just loop forever.
If you want to put a maximum number of iterations you should increment guessesTaken inside the loop.
while guessesTaken < 6:
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
else:
break
guess = int(input('Try again: '))
guessesTaken += 1
if guess == number:
print('Good job! You guessed my number in {} guesses!'.format(guessesTaken))
else:
print('Nope. The number I was thinking of was {}'.format(number))
Anyway, if you know you'll have at most 6 iterations you should just use a for loop instead:
for _ in range(6): # loop 6 times
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
else:
break
guess = int(input('Try again: '))
Related
Also the program doesn't show any error. And I can't find my error. When I run this code it says that my random number is either infinitely higher or lower
import random
def game1():
print("Hello I guessed a number, try to find it")
my_number = int(input("Guess the number:"))
a = random.randint(1,5)
number_of_tries = 1
while a != my_number:
if a > my_number:
print("Your number must be higher")
number_of_tries = number_of_tries+1
player_guess = int(input("Guess the number:"))
if a < my_number:
print("Your number must be lower")
number_of_tries = number_of_tries + 1
player_guess = int(input("Guess the number:"))
if a == my_number:
print("Congrats, you guessed the number")
print("Number of guesses is:", number_of_tries)
break
game1()
you assign the subsequent guesses to player_guess rather than my_number...
I'd tidy the code up to something like:
a = random.randint(1, 5)
number_of_tries = 0
print("Hello I guessed a number, try to find it")
while True:
my_number = int(input("Guess the number:"))
number_of_tries += 1
if a == my_number:
break
if a > my_number:
print("Your number must be higher")
if a < my_number:
print("Your number must be lower")
print("Congrats, you guessed the number")
print("Number of guesses is:", number_of_tries)
Required very little correction. just replace player_guess with my_number.
Basically, you are comparing a with my_number, and at first you store user input to my_number, if it is matched there is no problem. but when it don't match and the user requested to give another guess, the input stored in player_guess, but still compare a with player_guess (rather then with my_number). this should be corrected.
My son has this project he has to do in python and is stuck.
He needs to make a number guessing game. The code must generate a random secret number between 0 and 10, then give the user 5 attempts to guess that number, each guess if not correct must indicate if it is higher or lower than the secret random number. After each guess the code needs to display text stating what has happened. The code also needs to store all guesses and display them at the end. Needs to be made using loop, if, elif, else and an array or list code.
The attempt so far is below
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
from random import randint
x = [randint(0,10)]
counter = 0
guess = input("Enter guess:")
while counter < 5:
print("You have " + str(counter) + " guesses left")
counter = counter +1
if guess == x:
print("Congrats you got it")
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
else:
print("You lost")
break
Any help to correct my sons code would be appreciated as this project is due soon and he cannot access his tutor
This should do it. What the code does is explained in comments below.
You need to do x=randint(0,10) which will assign the random number to a variable, i.e x=4 rather than `x = [randint(0,10)], which assigns the random number to a list ,x=[4]```
Also you need to ask for a guess in the loop, instead of doing it only one before the loop started.
Also you would need to convert the string to an int for comparison i.e. guess = int(input("Enter guess:"))
print("Hi there, lets play a little guessing game. Guess the number between 0 and 10")
#Create a random number
from random import randint
x = randint(0, 10)
counter = 0
won = False
#Run 5 attempts in a loop
while counter<5:
#Get the guess from the user
guess = int(input("Enter guess:"))
counter = counter+1
#Check if the guess is the same, low or high as the random number
if guess == x:
print("Congrats you got it")
won = True
break
elif guess > x:
print("Too high")
elif guess < x:
print("Too low")
print("You have " + str(5 - counter) + " guesses left")
#If you didn't won, you lost
if not won:
print("The number was ", x)
print("You Lost")
So here are the corrections. So x has been initialized as array rather than an integer. So none of the comparisons with guess will be working. Also the counter logic is wrong. Rather than starting from zero, start from 5 which is the maximum number of chances and go from the reverse rather. Then at each if/elif loop append all the guesses and print it in the end.
Here is the corrected code
from random import randint
x = randint(0,10)
print(x)
counter = 5
guesses=[] #initalize an empty list to store all guesses
while counter != 0:
guess = input("Enter guess:")
if guess == x:
print("Congrats you got it")
guesses.append(guess)
break
elif guess > x:
print("Too high")
guesses.append(guess)
elif guess < x:
print("Too low")
guesses.append(guess)
else:
print("You lost")
break
counter = counter-1
print("You have " + str(counter) + " guesses left")
print(guesses)
Edit:
x = [randint(0,10)] wouldn't work as you are creating a list here instead of single guess
print("You have " + str(counter) + " guesses left") is also incorrect. You might instead set counter to 5 and check for counter > 0 and do counter -= 1, that way message can be fixed
Lastly to store all guesses you would need a variable
from random import randint
if __name__ == "__main__":
number_to_guess = randint(0,10)
guesses = []
for c in range(5,0,-1):
guessed = input("Enter guess:")
guessed = guessed.strip()
assert guessed.isnumeric()
guessed = int(guessed)
guesses.append(guessed)
if guessed == number_to_guess:
print("yes")
break
elif guessed > number_to_guess:
print("more")
else:
print("less")
c -= 1
print("pending guesses", c)
print("Expected - ", number_to_guess)
print("All guesses - ", guesses)
For a class assignment, I'm trying to make a number guessing game in which the user decides the answer and the number of guesses and then guesses the number within those limited number of turns. I'm supposed to use a while loop with an and operator, and can't use break. However, my issue is that I'm not sure how to format the program so that when the maximum number of turns is reached the program doesn't print hints (higher/lower), but rather only tells you you've lost/what the answer was. It doesn't work specifically if I choose to make the max number of guesses 1. Instead of just printing " You lose; the number was __", it also prints a hint as well. This is my best attempt that comes close to doing everything that this program is supposed to do. What am I doing wrong?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 0
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
while guess != answer and guess_count < guesses:
guess = int(input("Guess a number: "))
guess_count += 1
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
if guess_count >= guesses and guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
What about something like this?
answer = int(input("What should the answer be? "))
guesses = int(input("How many guesses? "))
guess_count = 1
guess_correct = False
while guess_correct is False:
if guess_count < guesses:
guess = int(input("Guess a number: "))
if answer < guess:
print("The number is lower than that.")
elif answer > guess:
print("The number is higher than that")
else: # answer == guess
print("You win!")
break
guess_count += 1
elif guess_count == guesses:
guess = int(input("Guess a number: "))
if guess != answer:
print("You lose; the number was " + str(answer) + ".")
if guess == answer:
print("You win!")
break
It's very similar to your program, but has a couple break statements in there. This tells Python to immediately stop execution of that loop and go to the next block of code (nothing in this case). In this way you don't have to wait for the program to evaluate the conditions you specify for your while loop before starting the next loop. If this helped solve your problem, it'd be great of you to click the checkmark by my post
The program is supposed to randomly generate a number between 1 and 10 (inclusive) and ask the user to guess the number. If they get it wrong, they can guess again until they get it right. If they guess right, the program is supposed to congratulate them.
This is what I have and it doesn't work. I enter a number between 1 and 10 and there is no congratulations. When I enter a negative number, nothing happens.
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
elif guess == number:
print "Congratulations! You guessed correctly!"
Just move the congratulations message outside the loop. You can then also only have one guess input in the loop. The following should work:
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
else:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
print "Congratulations! You guessed correctly!"
The problem is that in a if/elif chain, it evaluates them from top to bottom.
Move the last condition up.
if guess == number:
..
elif other conditions.
Also you need to change your while loop to allow it to enter in the first time. eg.
while True:
guess = int(raw_input("Guess a number: "))
if guess == number:
..
then break whenever you have a condition to end the game.
The problem is that you exit the while loop if the condition of guessing correctly is true. The way I suggest to fix this is to move the congratulations to outside the while loop
import random
number = random.randint(1,10)
print "The computer will generate a random number between 1 and 10. Try to guess the number!"
guess = int(raw_input("Guess a number: "))
while guess != number:
if guess >= 1 and guess <= 10:
print "Sorry, you are wrong."
guess = int(raw_input("Guess another number: "))
elif guess <= 0 and guess >= 11:
print "That is not an integer between 1 and 10 (inclusive)."
guess = int(raw_input("Guess another number: "))
if guess == number:
print "Congratulations! You guessed correctly!"
I have a little problem with my code, i'm trying to make a guess game, actually it is from a book, but i can't figure out what is wrong with it...
# A guess game program made in python
import random
guessesTaken = 0
print('Hello! What is your name, may i ask?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20')
while guessesTaken < 6:
print('Take a guess..')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your number guess is too low, guess again')
if guess > number:
print('Your number is too high! guess lower or something!')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed the right number in' + guessesTaken + 'guesses!')
if guess != number:
number = str(number)
print('Nah, The number i was thinking of was ' + number)
This is the error it's giving me..
Hello! What is your name, may i ask?
ygh
Well, ygh, I am thinking of a number between 1 and 20
Take a guess..
4
Your number guess is too low, guess again
Nah, The number i was thinking of was 7
Take a guess..
2
Traceback (most recent call last):
File "C:/Users/Owner/Desktop/guess.py", line 19, in <module>
if guess < number:
TypeError: unorderable types: int() < str()
Process finished with exit code 1
I'm using Pycharm as my IDLE and i'm also on windows..
Few changes in your code tho, instead of calling str you can use format()
# A guess game program made in python
import random
guessesTaken = 0
print('Hello! What is your name, may i ask?')
myName = input()
number = random.randint(1, 20)
print('Well, {}, I am thinking of a number between 1 and 20'.format(myName))
while guessesTaken < 6:
print('Take a guess..')
guess = input()
guess = int(guess)
guessesTaken += 1 # Instead of calling the variable itself then adding 1
if guess < number:
print('Your number guess is too low, guess again')
if guess > number:
print('Your number is too high! guess lower or something!')
if guess == number:
print('Good job, {}! You guessed the right number in {} guesses!'.format(myName,guessesTaken))
break # the beak goes here
if guess != number:
print('Nah, The number i was thinking of was {}'.format(number))
Also, your break was placed incorrectly because it will be executed before sending the print that you want, thus ending your code prematurely.