How do I end the loop when the game is won? - python

After making functions for how to check if guesses are right or not, I am having difficulty with getting it to say what I want.
ntries = 0
while ntries < 10:
ntries +=1
if test_guess(code,guess)==True:
print 'You win! You guessed the code in',ntries,'tries.'
elif test_guess(code,guess)==False:
guess = str(raw_input('Your guess: '))
print 'You lose!'
The problem is that when the player successfully guesses the code in, say, 8 tries, the result being printed is:
> You win! You guessed the code in 8 tries.
> You win! You guessed the code in 9 tries.
> You win! You guessed the code in 10 tries.
> You lose!
I realize it's because the while loop indicates that the loop keeps running when ntries is still less than 10. How do I have it so that it will only print the number of tries when won and stops there?

Break out of your loop with the break keyword inside of your if statement.
As an aside: your if-elif block is overly verbose. Since test_guess is returning something to be truthy, you could rewrite it as such. This also moves the ntries variable inside of the else condition, since it only makes sense to increment it if you actually guessed, but failed.
if test_guess(code, guess):
print 'You win! You guess the code in', ntries, 'tries.'
break
else:
ntries += 1
guess = str(raw_input('Your guess: '))

just use break
ntries = 0
while ntries < 10:
ntries +=1
if test_guess(code,guess)==True:
print 'You win! You guessed the code in',ntries,'tries.'
break
elif test_guess(code,guess)==False:
guess = str(raw_input('Your guess: '))
print 'You lose!'

Related

My iteration doesn't work when it runs after the first time

When I enter the correct word, it prints out congratulations, but when I enter it for the second or third try, it doesn't work
secret_word = "hello"
tries = 1
guess_word = input("Guess a word: ")
while tries < 3:
if secret_word != guess_word:
tries += 1
print("Sorry, word not found, you have", 4 - tries, "tries left")
guess_word = input("Guess a word")
if tries == 3:
print("Sorry, you are out of tries, better luck next time !!!")
break
else:
print("Congratulations! You've done it!")
break
In this section of code:
print("Sorry, word not found, you have", 4 - tries, "tries left")
guess_word = input("Guess a word")
if tries == 3:
print("Sorry, you are out of tries, better luck next time !!!")
you don't check to see whether the guess was right before telling the user they've lost. It might be easier if you base the loop on whether the guess was right, and use the tries counter to decide whether to break or continue:
secret_word = "hello"
tries = 0
while input("Guess a word: ") != secret_word:
tries += 1
if tries < 3:
print(f"Sorry, word not found, you have {3 - tries} tries left")
else:
print("Sorry, you are out of tries, better luck next time !!!")
break
else:
print("Congratulations! You've done it!")
It's better if you could put this line,
guess_word = input("Guess a word: ")
... in the while loop, so you wouldn't have 2 of the same lines.
You can also state the number of tries to 3 instead of 1. Set the number you want, and decrement downwards. To avoid code like, "4 - tries"
print("Sorry, word not found, you have", 4 - tries, "tries left")
secret_word = "hello"
tries = 3
while tries > 0:
guess_word = input("Guess a word: ")
if secret_word != guess_word:
tries -= 1
print("Sorry, word not found, you have", tries, "tries left")
if tries == 0:
print("Ran out of tries!")
break
else:
print("Congratulations! You've done it!")
break
Your current code only allows 2 tries to be made. The 3rd try even if you get it right, it will be thrown out. Let me know if there's anything wrong with my solution!
When you say while tries < 3 you only go up to 2 because thats the last whole number that's smaller than 3. If you want to include 3 you can change it to while tries <= 3
tries can never reach 3 as you have put while tries < 3
change it to tries<=3

While loops, if-else statements: Guess my number game

I'm a beginner using python, and am writing a "guess my number game". So far I have everything working fine. The computer picks a random number between 1 and 3 and asks the player to guess the number. If the guess is higher than the random number, the program prints "Lower", and vice versa. The player only has 5 tries, and when they run out, the player gets a message and the game ends. If the player guesses correctly, they are congratulated and the game ends. However, sometimes when the number is guessed correctly, the program doesn't print the congratulatory message and I can't figure out why...
import random
print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 100.")
print("Guess carefully, you only have 5 tries!.\n")
#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 4
#guessing loop
while guess != the_number:
if guess > the_number:
print("Lower...")
elif guesses <= 0:
print("Sorry, you're out of guesses! Try again...")
break
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
To answer your original question about the lack of congratulatory message for correct number, end the code with input(), to ensure it does not terminate before displaying the last message.
Order of calculation:
give input guess
reduce guesses (starting at 5), increase tries (starting at 1)
immediate break if guesses == 0
evaluate guess (lower, higher or equal, which would end while loop)
import random
print("\tWelcome to 'Guess My Number'!:")
print("\nI'm thinking of a numer between 1 and 3.")
print("Guess carefully, you only have 5 tries!.\n")
#sets initial values
the_number = random.randint(1,3)
guess = int(input("Take a guess: "))
tries = 1
guesses = 5
#guessing loop
while guess != the_number:
tries += 1
guesses -= 1
if guesses == 0:
print("Sorry, you're out of guesses! Try again...")
break
elif guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
guess = int(input("Take a guess: "))
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
input()
Assuming everything else works, un-indent the final check. You can't check guess == the_number while it isn't equal
#guessing loop
while guess != the_number:
# do logic
# outside guessing loop
if guesses > 0:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
If you guess the number in your first try, the program will require another guess nevertheless since
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
comes before
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
when you already asked for a guess outside the loop. You should only ask for input inside the loop:
the_number = random.randint(1,3)
tries = 0
guesses = 5
#guessing loop
guess = None
while guess != the_number:
guess = int(input("Take a guess: "))
tries += 1
guesses -= 1
if guess > the_number:
print("Lower...")
elif guess < the_number:
print("Higher...")
if guess == the_number:
print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")
if guesses <= 0:
print("Sorry, you're out of guesses! Try again...")
break

Python Number Guessing Game Need Help Avoiding Counting Duplicates in "Number of Guesses"

I am brand new to learning Python and am building a very simple number guessing game. The user guesses a number between 1-100, and are given feedback on whether their guess is too low or too high. When they guess the number correctly, the program tells them how many guesses they took. What I need help with: telling the user when they guessed a duplicate number if they have entered it already. I also want to exclude any duplicate guesses from the final guess count. What is the easiest way to do this?
Here is my game so far:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
guess = int(input(""))
tries = 0
while guess != the_number:
if guess > the_number:
print("Lower")
if guess < the_number:
print("Higher")
guess = int(input("Guess again: "))
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
Keep track of the numbers guessed, only increasing if the user has not guessed a number already in our guessed set:
import random
print("Guess a number between 1-100")
the_number = random.randint(1, 100)
tries = 0
# store all the user guesses
guessed = set()
while True:
guess = int(input("Guess a number: "))
# if the guess is in our guesses set, the user has guessed before
if guess in guessed:
print("You already guessed that number!")
continue
# will only increment for unique guessed
tries += 1
if guess == the_number:
print("You win! The number was", the_number)
print("And it only took you", tries, "tries!\n")
break
elif guess > the_number:
print("Lower")
# if it's not == or >, it has to be <
else:
print("Higher")
# add guess each time
guessed.add(guess)
You also had some logic in regard to your ordering like taking a guess outside the loop which could have meant you never entered the loop if the user guessed first time.
this is how you should write the code.
import random
debug = True
def number_guessing():
previous_guesses = set()
tries = 0
print("Guess a number between 1-100")
random_number = random.randint(1, 100)
while True:
guess = int(input())
if guess in previous_guesses:
print("You already tried that number")
continue
previous_guesses.add(guess)
tries += 1
if random_number < guess:
print(f"Lower => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif random_number > guess:
print(f"Higher => previous attempts [{previous_guesses}] tries [{tries}]") if debug is True else None
elif guess == random_number:
print("You win! The number was", random_number)
print(f"And it only took you {tries} attempt{'s' if tries>1 else ''}!\n")
break
number_guessing()

Error with my game?

from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
def guess():
guess = int(input("What is your guess?"))
if guess > 10:
print ("Insert value between 1 and 10")
guesses_left += 1
guess()
if guess == random_number:
print ("You win")
break
guesses_left -= 1
else:
print ("You lose")
I am making this game where random numbers are formed and the user guesses the random number to win the game. However, I want to implement a safety that if the guess goes over 10, then it will print "enter value from 1 to 10" (see the code) and also add 1 to the guess left. I made this into a function so that the print message keeps displaying itself until the user puts all his guesses from 1 to 10. I am getting an error in that function itself :(
Also, how can I keep displaying the print message without functions? I know how to do it with while loop but is there a better way to do it?
You don't need the function at all, since you don't call it more than once.
A good way to think about the problem is that the program starts with a state of not knowing what the players guess is. You can represent this as 0. Then the while loop checks to see if the guess is >=1 AND <=20. Since the first time around, it's not, the loop would ask for a guess between 1 and 10.
Several notes here:
1) Remove the definition of the guess function outside of the while loop.
2) Watch the indentation. It's meaningful in Python
3) I merged the guess function with the main code, and it's still pretty readable
4) You can avoid having to increment guesses_left by 1 if you don't decrement it
5) I really hope you're trying to learn programming, and not having us complete your homework for you. Python can be very powerful, please continue to learn about it.
from random import randint
random_number = randint(1, 10)
guesses_left = 3
# Start of the game
win=False
while guesses_left>0:
guess=int(input("What is your guess?"))
if guess==random_number:
win=True
break
elif guess>10:
print("Insert value between 1 and 10")
continue
else:
guesses_left -= 1
if win:
print("You win")
else:
print("You lose")
from random import randint
random_number = 10 # randint(1, 10)
guesses_left = 3
# Start of the game
while guesses_left != 0:
guess = int(input("Guess a number between 1 and 10: "))
if guess > 10:
print "(error: insert a value between 1 and 10)"
guesses_left = guesses_left - 1 #add if you want to dock them a guess for not following instructions :)
else:
if guess is random_number:
print ("You win!")
break
else:
print "Nope!"
guesses_left = guesses_left - 1
if guesses_left is 0:
print "Wah Wah. You lose."
My code is probably more verbose than it needs to be but it does the trick. There are a couple problems with the way you wrote the script.
Like Hack Saw said, I don't think you need the function.
Indentation is off. This matters a lot to python
Good luck in class! :)

Guess My number game with limited number of guesses

I'm new to python and I'm trying to make the guess my number game with a limit of only 5 guesses, everything I've tried so far has failed. how can I do it?, I forgot to mention that I wanted the program to display a message when the player uses all their guesses.The code below only prints the "You guessed it" part after the 5 guesses whether they guess it or not.
import random
print ("welcome to the guess my number hardcore edition ")
print ("In this program you only get 5 guesses\n")
print ("good luck")
the_number = random.randint(1, 100)
user = int(input("What's the number?"))
count = 1
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5:
break
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
input ("\nPress enter to exit")
Your edit says you want to differentiate between whether the loop ended because the user guessed right, or because they ran out of guesses. This amounts to detecting whether you exited the while loop because its condition tested false (they guessed the number), or because you hit a break (which you do if they run out of guesses). You can do that using the else: clause on a loop, which triggers after the loop ends if and only if you didn't hit a break. You can print something only in the case you do break by putting the print logic right before the break, in the same conditional. That gives you this:
while user != the_number:
...
if count == 5:
print("You ran out of guesses")
break
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
However, this puts code for different things all over the place. It would be better to group the logic for "guessed right" with the logic for warmer/colder, rather than interleaving them with part of the logic for how many guesses. You can do this by swapping where you test for things - put the 'is it right' logic in the same if as the warmer/colder, and put the number of guesses logic in the loop condition (which is then better expressed as a for loop). So you have:
for count in range(5):
user = int(input("What's the number?"))
if user > the_number:
print("Lower")
elif user < the_number:
print("Higher")
else:
print("You guessed it!!, the number is", the_number, "and it only"\
" took you", count , "tries")
break
else:
print("You ran out of guesses")
You have two options: you can either break out of the loop once the counter reaches a certain amount or use or a for loop. The first option is simplest given your code:
count = 0
while user != the_number:
if user > the_number:
print ("Lower")
elif user < the_number:
print ("Higher")
user = int(input("What's the number?"))
count += 1
if count == 5: # change this number to change the number of guesses
break # exit this loop when the above condition is met

Categories

Resources