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.
Related
I am using The Big Book of Small Python projects to increase my skills in python, and on the very first project, which is making a simple logic game, On the first try, the code goes all the way however if you get it wrong you it won't run properly.
Here is the code and a description of the game, the while loop with chances is supposed to run for the whole game, until you run out of chances, the second while loop is supposed to run in case user enters below or more than length three for the number
import re
import random
#In Bagels, a deductive logic game, you
#must guess a secret three-digit number
#based on clues. The game offers one of
#the following hints in response to your guess:
#“Pico” when your guess has a correct digit in the
#wrong place, “Fermi” when your guess has a correct
#digit in the correct place, and “Bagels” if your guess
#has no correct digits. You have 10 tries to guess the
#secret number.
choice_of_nums=['123','345','674','887','356','487','916']
random_three_num=random.choices(choice_of_nums)
count_bagel=0
count_fermi=0
Chances=10
while Chances!=0:
guess = input(f'Guess the three digit number! You have {Chances} to guess! ')
while len(guess)!=3:
guess=input('You must choose a three digit number! Try again! ')
for i in range(0,len(random_three_num)):
if guess==random_three_num:
print('YOU WIN! Well done')
break
elif guess[i] not in random_three_num:
count_bagel+=1
if count_bagel==len(random_three_num):
print('Bagels')
Chances=Chances-1
elif guess[i]==random_three_num[i]:
count_fermi+=1
Chances=Chances-1
print('Fermi')
elif guess in random_three_num:
print('Pico')
import random
choice_of_nums = ['123', '345', '674', '887', '356', '487', '916']
random_three_num = random.choice(choice_of_nums)
count_bagel = 0
count_fermi = 0
chances = 10
while chances > 0:
guess = input(f'Guess the three digit number! You have {chances} to guess! ')
while len(guess) != 3:
guess = input('You must choose a three digit number! Try again! ')
while not guess.isdigit():
guess = input('You must choose integer values! ')
number_is_present = any(number in guess for number in random_three_num)
if guess == random_three_num:
print('YOU WIN! Well done')
chances = 1 # combined w/ the last line, chances will become = 0
elif not number_is_present:
print('Bagel')
else:
index_is_right = False
for i in range(len(guess)):
if guess[i] == random_three_num[i]:
index_is_right = True
if index_is_right:
print('Fermi')
else:
print('Pico')
chances -= 1
(06/28/22) added chances = 1 if the guess is right, so to exit the while loop
random.choices returns a list
you don't need the re module
use snake case as suggested in PEP8
The break after print('YOU WIN! Well done') exits the for loop not the while loop. Put Chances = 0 before the break:
if guess==random_three_num:
print('YOU WIN! Well done')
Chances = 0
break
You should never check a while loop with a condition like x != 0. Always use <= or >=. The reason being, that if somehow the number zero is skipped and you end up at -1 then the loop will still exit.
Couldn't your check if guess==random_three_num: be done before the for loop? Then the break statement would actually break the while loop. Now it's only breaking the for loop. This is one reason that could lead to a infinite loop.
Your second to last line elif guess in random_three_num: should probably be elif guess[1] in random_three_num:.
Chances=Chances-1 could probably be outside the for loop also, as the number of chances should decreasing only one per guess. Currently the number of chances decreases up to 3 times during the for loop (every time you hit 'Fermi'). This could lead to issue described in "1."
How do I make a specific line of code execute only once inside a while loop?
I want the line:
"Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.
Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")
You can create a flag variable, e. g.
print_username = True
before the while loop. Inside the loop uncheck it after loop's first iteration:
if print_username:
guess = input("Hello %s, please enter your guess: " % p1)
print_username = False
else:
guess = input("Try a new guess:")
You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.
To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:
# [start identical]
while guess != number and guess != "exit":
guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0
else "Try again: ")
# [rest identical]
See Does Python have a ternary conditional operator?
The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).
You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well
A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.
You should ask for the username outside of the loop and request input at the beginning of the loop.
Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)
Before writing this question, I looked for something similar in the forum, but did not find any. So here is my version of the guessing game. I want the user to guess a number from 0 to 10 that the computer has "thought". But I want to calculate the difference of the numbers and show whether the user is close or not to figuring out the correct number.
My code is as follows:
import math
import random
intnum = random.randrange(0,11)
print(intnum)
print ("The computer generated a random number from 0 to 10! Can you guess it?")
guess = 0
while guess != intnum:
guess = int(input ("Pick a number!!: "))
num = abs(guess-intnum)
print (num)
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I print the computers number and the difference, to find my bugs easily. There is a logical error that I cannot solve. If the computer generates a number 9, and I guess a number 1, the difference is 9-1=8. But the program, prints "You are less than 2 away", which is incorrect. What am I doing wrong? I would like to use this in a larger version with more numbers but for starters I scaled it down a bit to find the correct logic and syntax.
This block needs rewriting from
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
to
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 and num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 and num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I understand what you're trying to do with the "or"s in your initial code block, but the computer will think differently, and in this case, "and" is your friend.
The right statement is:
elif (num<=2):
print ("You are less than 2 away. Keep going!")
The condition you are using does not do what you want.
You need to check if a number lies in an interval. To do so, you need to ensure that the number is greater that the lower bound and lower than the upper bound
You need to change the or to and in your conditions
I created a guess the number program and used a while loop to allow the user to continue guessing until he/she could get it right, as seen here:
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
The problem is, when I am trying to guess the number, it will randomly end, whether me guessing the first time, 4 times, or 30 times. Also, I originally had,
guess = int(raw_input('>'))
in place of,
guess = "yes"
and replaced it to get rid of the extra and useless raw_input i'd initially need to add into terminal. Why am i able to make it equal "yes" and why doesn't it matter what I put there?
Example of Bug:
Guess the number, between 1 and 6
>3
Too High
2
>4
Too Low
5
>6
Too High
5
>3
Too High
1
>2
Too High
1
>5
Good job! You got it right!
5
------------------
(program exited with code: 0)
Press return to continue
It worked that time, and now:
Guess the number, between 1 and 6
>3
Too Low
4
------------------
(program exited with code: 0)
Press return to continue
The issue you have is that your while loop is testing if number matched guess after picking a new number value but before getting a new guess. This means that you'll say the player guessed wrong, but they they become right afterwards and the loop will end.
Try this instead:
import random
print "Guess the number, between 1 and 6"
guess = 'y' # the values set here don't actually matter, they just need to be different
number = 'x'
while guess != number:
number = random.randint(1, 6)
guess = int(raw_input('>'))
if guess == number:
print "Good job! You got it right!"
elif guess > number:
print "Too High"
print number
elif guess < number:
print "Too Low"
print number
I've also changed your use of random.randrange to random.randint, which will make it actually return 6s some of the time (randrange excludes the upper bound).
guess = "yes" works because guess != number will always be True on the first check in the while loop, at which point the user is asked for input. Also, in the if block, put the break statement after all the print's.
import random
number = random.randrange(1, 6)
print "Guess the number, between 1 and 6"
guess = "yes"
while guess != number:
guess = int(raw_input('>'))
if guess == number:
break
print "Good job! You got it right!"
print number
break
elif guess > number:
print "Too High"
print number
number = random.randrange(1, 6)
break
elif guess < number:
print "Too Low"
print number
number = random.randrange(1, 6)
break
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.