My next task is modifying current code. In a previous exercise, I've written a basic application that covers a numbers guessing game. The code is as follows: -
# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
My task is to modify this so that there is a limited number of goes before a failure message is given to the user. Thus far, the chapter has covered "if, elif, else, for, loops, avoiding infinte loops." As such, I'd like to limit my response to these concepts only. For loops are covered next chapter.
What have I tried?
So far, I've tried amending the block in another while loop using 5 goes and the tries variable but it doesn't seem to work.
# guessing loop
while tries < 6:
guess = int(input("Take a guess: "))
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
tries += 1
input("You didn't do it in time!")
input("\n\nPress the enter key to exit.")
Any pointers or highlighting what I've missed would be appreciated plus any explanation as to what I'd missed. Teaching myself to think programatically is aslo proving tricky.
What doesn't work
When I run it, the loop conditions't don't appear to work. My idle feedback is as follows.
This means my question can be summarised as
Where is my looping logic broken?
>>> ================================ RESTART ================================
>>>
Welcome to 'Guess My Number'!
I'm thinking of a number between 1 and 100.
Try to guess it in as few attempts as possible.
Take a guess: 2
Take a guess: 5
Higher...
You didn't do it in time!
Press the enter key to exit.
The problem is that your break statement is not indented to be included in your elif:
elif guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
Thus, the loop always stops after the first iteration. Indent the break to be included within the elif and it should work.
The break is not in the conditional.
Add a tab before it.
Related
Right now, I am working on Chapter 3 of the book Python for the absolute beginner.
One of the challenges at the end of chapter 3 is to "Modify the Guess My Number game so that the player has a limited number of guesses" and that if the player fails to get the correct amount of guesses, a message should be displayed.
The code looks like this:
# Guess My Number
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
# guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input("\n\nPress the enter key to exit.")
From what I can see so far, I need to add a variable that counts how many lives a player has, which is set to an amount at the beginning, like 10 and an if command should be used to make sure that, when the player uses all their lives, the message is displayed.
However, I am unsure where to place the if command in the existing code.
Well, If I were you I would make a game loop instead of the guessing loop. And then I would just break the game loop when I reach the guessing limit. However if you wanna keep your code you can use this.
while guess != the_number:
if tries == 3: # Replace 3 with the limit you'd like to use
print("You lost :(")
exit()
else:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
Also in your case don't use break, it will still cause to print in the end the winning msg
(the spacing might be a little bit off so u may need to fix it)
After you say tries+=1, put an if statement. Your code should look like this:
if tries>3:
print("Game Over")
break()
import random
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")
# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1
while tries < 8:
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
if tries == 8:
print("You failed to guess my number")
input("\n\nPress the enter key to exit.")
You can also do it this way
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 7 years ago.
import random
print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")
random_integer=random.randint(1,25)
tries=0
tries_remaining=10
while tries < 10:
guess = input("Try to guess what random integer I'm thinking of, {}! ".format(name))
tries += 1
tries_remaining -= 1
# The next two small blocks of code are the problem.
try:
guess_num = int(guess)
except:
print("That's not a whole number! ")
tries-=1
tries_remaining+=1
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
break
elif guess_num == random_integer:
print("Nice job, you guessed the right number in {} tries! ".format(tries))
break
elif guess_num < random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
elif guess_num > random_integer:
if tries_remaining > 0:
print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining. ".format(int(tries_remaining)))
continue
else:
print("Sorry, but the integer I was thinking of was {}! ".format(random_integer))
print("Oh no, looks like you've run out of tries! ")
I'll try to explain this as well as I can... I'm trying to make the problem area allow input for guesses again after the user inputs anything other than an integer between 1 and 25, but I can't figure out how to. And how can I make it so that the user can choose to restart the program after they've won or loss?
Edit: Please not that I have no else statements in the problems, as there is no opposite output.
Use a function.Put everything in a function and call the function again if the user wants to try again!
This will restart the complete process again!This could also be done if the user wants to restart.
Calling the method again is a good plan.Enclose the complete thing in a method/function.
This will solve the wrong interval
if not guess_num > 0 or not guess_num < 26:
print("Sorry, try again! That is not an integer between 1 and 25! ")
continue
For the rest, you can do something like this
create a method and stick in your game data
def game():
...
return True if the user wants to play again (you have to ask him)
return False otherwise
play = True
while play:
play = game()
I try to make a simple guessing game with the "Python programming for absolute beginner" book. Game should generate random number from 0 to 10, then take player's guesses and print "Too high!", if the guessed number is too high, or "Too low!" if the number is too low. After each guess, game adds 1 to the number of guesses. It ends, when the player's guess is correct and displays number of guesses taken.
My code is exactly the same, as code in the book, but when I run it in IDLE, I get "invalid syntax" error on "tries += 1" line. When I delete this line, the error happens on the next line etc. When I run it from file, it just opens and closes immediately. I use Python 3.4.1.
import random
number = random.randint(0,10)
player_guess = int(input("What's your guess?"))
tries = 1
while player_guess != number:
if player_guess > number:
print("Too high!")
else:
print("Too low!")
player_guess = int(input("What's your guess?")
tries += 1
print("Congrats!")
print(tries)
input("\n\nPress any key...")
You're missing a closing parentheses ) on the above line to complete the int conversion.
So I'm learning python and I'm trying to code a simple guess my number game where you only have 5 guesses or the game ends. Im really having trouble with the while loop not recognising that the number has been guessed or the guess limit has been reached. Is there a better way of formatting my functions also. Thanks for any and all help, first time using this site.
# Guess my number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money
import random
GUESS_LIMIT = 5
# functions
def display_instruct():
"""Display game instructions."""
print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.")
print("\nHARDCORE mode - You have 5 tries to guess the number!\n")
def ask_number(question, low, high, step = 1):
"""Ask for a number within a range."""
response = None
while response not in range(low, high, step):
response = int(input(question))
return response
def guessing_loop():
the_number = random.randint(1, 100)
guess = ask_number("\nTake a guess:", 1, 100)
tries = 1
while guess != the_number or tries != GUESS_LIMIT:
if guess > the_number:
print("Lower...")
else:
print("Higher...")
guess = ask_number("Take a guess:", 1, 100)
tries += 1
if tries == GUESS_LIMIT:
print("\nOh no! You have run out of tries!")
print("Better luck next time!")
else:
print("\nYou guessed it! The number was", the_number)
print("And it only took you", tries, "tries!")
def main():
display_instruct()
guessing_loop()
# start the program
main()
input("\n\nPress the enter key to exit")
Your while condition will be true as long as you haven't hit the guess limit.
while guess != the_number or tries != GUESS_LIMIT:
You should join those conditions with and, not or. The way you have it now, the entire condition will be true because tries != GUESS_LIMIT is true, even if guess != the_number is false.
Or you can break your cycle explicitly with break statement. But previous answer is more correct in a sense you should really understand conditions you're setting for the loop.
I am learning Python on Codecademy, and I am supposed to give the user 3 guesses before showing "you lose". I think my code allows 3 entries, but the website shows "Oops, try again! Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?" unless the user guesses correctly within 3 trials. Can someone tell me what's wrong?
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
guess= int(raw_input("Please type your number here:"))
while count < 2:
if guess==random_number:
print "You win!"
break
else:
guess=int(raw_input("Please guess again:"))
count+=1
else:
print "You lose!"
print random_number
Your loop will indeed ask the user for three guesses. (As can be trivially seen by running the code—ignore those other answers telling you to change the loop condition, that's the wrong solution.)
The problem with your loop is a more subtle one: because of the way it's structured, the third guess is never tested! You can see this by setting random_number to a constant and guessing wrong twice, then right on the last try; you still lose.
Your best bet is to use a more straightforward loop structure, where the asking and the checking happens in the same iteration of the loop.
for attempt in xrange(3):
guess = int(raw_input("Please enter a number: "))
if guess == random_number:
print "You win!"
break
print "Wrong! Try again."
else:
print "You lose! The number was", random_number
If you want a different prompt on the second and subsequent guesses, try this:
prompt = "Please enter a number"
for attempt in xrange(3):
guess = int(raw_input(prompt + ": "))
if guess == random_number:
print "You win!"
break
prompt = "Wrong! Try again"
else:
print "You lose! The number was", random_number
You need while count <= 2. Your count starts at 0. Then it goes through the body of your loop once. Then it gets incremented to 1. Then it goes through your loop body another time. Finally, once it increments to 2, your while condition evaluates to false, and the loop body doesn't execute a third time.
Be careful with corner cases when you're setting up conditions. :)
The condition should be:
while count < 3:
To make it easier to understand, I suggest you start the counter in count = 1 and write the condition like this:
while count <= 3:
Now it's more clear that exactly 3 repetitions are allowed. But let's see why your code was wrong:
count starts at 0, and it's true that 0 < 2, so we enter the loop
At the first failed attempt, count gets incremented to 1, and it's true that 1 < 2 so we enter the loop once more
At the second failed attempt, count gets incremented to 2, and it's no longer true that 2 < 2 so we exit the loop
So you see, only two attempts were being considered.