I'm new to Python but I can't seem to figure out why the declared "attempt" variable is not decremented if an incorrect attempt is submitted.
My thoughts are once a guess is submitted if it's not equal to the correctAnswer then the variable attempts should be decremeted by 1 so the print statement would say "You have 2 attempts left.
# You have 3 attempts to guess the correct word. If you don't you lose!
attempts = 3
correctAnswer = 32
while attempts != 0:
guess = input("How old is Dad?")
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
print("You lose!")
print("You are right!")
The variable is being updated but you have a problem with the input comparison and your print logic is kinda backwards, making the output look strange. The input function returns strings, and strings are never equal to integers. You need to convert the string to an integer. That will fail if you are given bad input so you can either check the value before you attempt a conversion or use a try/except block to catch errors.
You could pull the final success/failure condition out of the loop:
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1 #This should decrement if the attempt is incorrect
print("You have " + str(attempts) + " left")
else:
break
if attempts:
print("You are right!")
else:
print("You lose!")
But python while loops have an else clause that only runs if the while is not terminated with a break. Add a break to the success path and it will catch the fail path.
attempts = 3
correctAnswer = 32
while attempts != 0:
guess_str = input("How old is Dad?")
if not guess_str.isdigit():
attempts = attempts - 1
print("Please enter a number, yYou have " + str(attempts) + " left")
continue
guess = int(guess_str)
if guess != correctAnswer:
attempts = attempts - 1
print("You have " + str(attempts) + " left")
else:
print("You are right!")
break
else:
print("You lose!")
Related
This question already has answers here:
Comparing a string to multiple items in Python [duplicate]
(3 answers)
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
I'm experimenting with the basic guessing game script that gets shown to you as part of "Automate The Boring Stuff With Python".
I want the game to loop infinitely until someone says anything
other than "Yes" or "yes" in response to "Would you like to try again?" at which point I would like the loop to break and the script to die.
However, even if someone inputs something else, the script always behaves as if "Yes" has been inputted in response. I have no idea why.
Here's the code:
#Guess the number game
import random
def the_game(): # This is the game itself
try:
global secretNumber
global guessesTaken
global guess
global try_again
secretNumber = random.randint(1,20)
for guessesTaken in range(1, 7):
print("Take a guess.")
guess = int(input())
if guessesTaken - 6 == 0:
print("You have " + str(6 - guessesTaken) + " attempts remaining. Boo.")
elif guess < secretNumber:
print("Try again. Higher this time. You have " + str(6 - guessesTaken) + " attempts remaining.")
elif guess > secretNumber:
print("Nope. Less. You have " + str(6 - guessesTaken) + " attempts remaining.")
else:
break
except ValueError:
print("Please enter a number.")
the_game()
if guess == secretNumber:
if guessesTaken == 1:
print("You did it in " + str(guessesTaken) + " attempt. I bet you're proud of yourself.")
else:
print("You did it in " + str(guessesTaken) + " attempts. I bet you're proud of yourself.")
else:
print("It was " + str(secretNumber) + ". You suck " + name + ".")
print("Would you like to try again? Yes or no.")
try_again = input()
print("Hello. What is your name?")
name = input()
print("Well, " + name + ". I am thinking of a number between 1 and 20")
while True:
the_game()
## I want the game to loop infinitely until someone says anything
## other than "Yes" or "yes" in response to "Would you like to try again?"
## at which point I would like the loop to break and the script to die.
## However, even if someone inputs something else, the script always behaves
## as if "Yes" has been inputted in response. I have no idea why.
if try_again == "Yes" or "yes":
print("Here we go again.")
the_game()
else:
print("Goodbye!")
break
exit()
I'm making a number guessing game on Python for a school project and have come upon two problems that I cannot find a solution to. I have two questions but decided to post as one question in order to not spam stack overflow.
How do I add a while true loop inside a while loop?
I found a neat trick where you can ask the game to keep asking for a number instead of ending the whole code when someone accidentally inserts a letter.
while True:
try:
guess = int(input("Guess which number I am thinking of: "))
except ValueError:
guess = print("That's not a number, guess a NUMBER!")
continue
else:
break
My game allows the player to guess six times before failing the game. I do this with a while loop so I how do I add the above while true loop into the while loop that I already have:
while GuessesTaken < 6:
GuessesTaken = GuessesTaken + 1;
GuessesLeft = 6 - GuessesTaken;
guess = input("Guess which number I am thinking of: ")
guess = int(guess)
if guess < hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess < hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess > hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess > hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess==hidden:
break
When variables are defined outside of loop but used within loop, it says the variable is not defined.
I have no idea how to fix the first problem but I have tried a lot of things in an attempt to solve the second problem.
def main():
hidden = random.randint(1,100)
while GuessesTaken < 6:
GuessesTaken = GuessesTaken + 1;
GuessesLeft = 6 - GuessesTaken;
guess = input("Guess which number I am thinking of: ")
guess = int(guess)
if guess < hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess < hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess > hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess > hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess==hidden:
break
This code comes out with a
NameError: name 'hidden' is not defined
But if I add a
hidden = random.randint(1,100)
at the top underneath this part of the code
score = 0
GuessesTaken = 0
currenttime = str(datetime.now())
currenttime = (
currenttime[0:19])
yesList =("yes", "sure", "yeah", "ye", "yea", "y", "fine", "okay", "ok", "yep")
it works until I get to this point of the game
if guess!=hidden:
hidden=str(hidden)
print("Fail! The number I was thinking of was " + hidden)
restart=input("Would you like to play again?").lower()
if restart in yesList:
main()
and the code stops working.
The last thing I tried was adding the while true loop into def main(): like this
def main():
hidden = random.randint(1,100)
while GuessesTaken < 6:
GuessesTaken = GuessesTaken + 1;
GuessesLeft = 6 - GuessesTaken;
guess = input("Guess which number I am thinking of: ")
guess = int(guess)
if guess < hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess < hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess > hidden and GuessesLeft==0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
break
elif guess > hidden and GuessesLeft > 0:
GuessesLeft=str(GuessesLeft)
print("Your guess is too low, you have " + GuessesLeft + " guesses left")
elif guess==hidden:
break
This came out with a different error message.
NameError: name 'guess' is not defined
Constants are spelled LIKE_THIS, variables and functions like_this and classes LikeThis.
The number of guesses taken has to be initialized for each game.
var += 1 is the same than var = var + 1
Using literals (such as the 6 you were using) several times in the code is a good sign that it should be moved to a constant. It also allows you to change this pretty fast.
You are already breaking the loop, so checking again if the remaining guesses is 0 will just slow your code.
You are doing the same thing in several places when they can be done only once.
The code would be something like:
import random
YES_LIST = ("yes", "sure", "yeah", "ye", "yea", "y", "fine", "okay", "ok", "yep")
MAX_GUESSES = 6 # WIN RATES: 1 -> 1% ; 2 -> 3% ; 3 -> 7%
# 4 -> 15% ; 5 -> 31% ; 6 -> 63%
def guess_game():
hidden = random.randint(1, 100)
guesses_taken = 0
while guesses_taken < MAX_GUESSES:
guess = int(input("Guess which number I am thinking of: "))
guesses_taken += 1
guesses_left = MAX_GUESSES - guesses_taken
if guess == hidden:
break
if guess < hidden:
print("Your guess is too low, you have {} guesses left.".format(guesses_left))
else:
print("Your guess is too high, you have {} guesses left.".format(guesses_left))
else:
# An else of a while loop will only be executed if we do NOT break from it,
# this is, this part will only be executed if it did not find out the answer
return False, hidden # We return False meaning it failed and the hidden number
# As we returned already if he didn't guess, this will only be executed if he did guess
return True, hidden # We return True meaning it succeeded and the hidden number
def main():
restart = True
score = 0
games = 0
while restart:
success, number = guess_game()
games += 1
if success:
score += 1
print("Congrats, you guessed my number.")
else:
print("Fail! The number I was thinking of was {}.".format(number))
restart = input("Want to play again?").lower() in YES_LIST
print("Thank you! You guesses {} out of {} numbers.".format(score, games))
main()
I added some code to allow the user to replay as you were showing hints that you were doing that yourself too.
import random
import time
numOfGuesses = 0
guess = ''
playername = ''
numbertoguess = 0
MAX_GUESS = 10
#======================
playername = input ('What is your name:')
numbertoguess = random.randint (1, 100)
input("hello, " + playername + ", Guess the number I am thinking of (hint: its between 1 and 100")
#======================
while numOfGuesses < MAX_GUESS:
guess = int(input("What is your guess:"))
numOfGuesses += 1
time.sleep(1)
if guess < numbertoguess:
print ('Higher')
if guess > numbertoguess:
print ('Lower')
elif numOfGuesses > MAX_GUESS:
sys.exit()
else:
sys.exit()
#======================
if guess == numbertoguess:
print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")
elif guess != numbertoguess and numOfGuesses == 10:
print ("awe so close," + playername + ".")
print ("the number was" + str(numbertoguess) +".")
when you finish one guess instead of telling you to go "higher" or "lower" the code runs over them and doesn't print either. I'm so new to python if someone could help me that would be great.
Ok, a few problems here.
1) Python treats newlines as semicolons in C-like languages, so
input("hello, " + playername + ", Guess the number I am thinking of
(hint its between 1 and 100")
will throw a syntax error. To encode a newline, use the escape sequence "\n"
input("hello, " + playername + ", Guess the number I am thinking of \n(hint it's between 1 and 100")
This looks like a copy + paste issue though.
2) Python uses indentations to figure out where your blocks are. So all of the statements in your loop body MUST begin with the same number of spaces / tabs as the rest. So your while loop should look like (indentation wise)
while numOfGuesses < MAX_GUESS:
guess = int(input("What is your guess:"))
numOfGuesses += 1
time.sleep(1)
if guess < numbertoguess:
print ('Higher')
if guess > numbertoguess:
print ('Lower')
elif numOfGuesses > MAX_GUESS:
sys.exit()
else:
sys.exit()
I believe this is causing the issues you specified in your question title. Since the while loop is only executing the line guess = int(input("What is your guess:")) because it is the only one indented properly.
Note: you cannot mix tabs and spaces, python will have a fit and no soup for you
Also indentation styles are typically 4 spaces or 1 tab. Single space indents WILL give you headaches after a while.
3) If you need a delay, the proper function is time.sleep()
4) You have two if statements in your while body, so should the guess pass the if guess < numbertoguess: it will continue to the next if guess > numbertoguess: and fail it. Then it will jump to the else body, which is a system exit / break statement. Either will cause the game to end prematurely.
Change if chain to:
if guess < numbertoguess:
print ('Higher')
elif guess > numbertoguess:
print ('Lower')
elif numOfGuesses > MAX_GUESS:
break;
else:
break;
5) You have sys.exit() but you forgot to import sys. Also exit() does not need to be imported, you can use it without the sys module.
6) exit() quits your program. Nothing after the while loop will run if one of those elif / else statements executes. The statement you are looking for is likely the break statement, which continues program execution on the next line after the loop.
7) Same as number 1), you've got a statement split across two lines here
print ("You are right," + playername + ",you guessed it in "+str
(numOfGuesses) + "tries")
Fix to
print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")
NOTES
Style wise, use 4 space or 1 tab indentations. It makes things easier to read. Also use newlines to separate logical blocks in code. You can use #=========== to denote important blocks or huge logical blocks.
That's not to say you cannot have no newlines and cannot use #=========== for logical blocks, but people reading your code will hate you.
Your strings are missing some formatting here and there
You've hardcoded the max guesses here at the bottom: elif guess != numbertoguess and numOfGuesses == 10: In fact, you don't really need that check, since you've checked for a correct answer above.
if guess == numbertoguess:
print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")
else:
print ("awe so close," + playername + ".")
print ("the number was" + str(numbertoguess) +".")
This works because there are two logical states that the user can be in at the moment: guessed correctly or guessed incorrectly MAX_GUESS times. Should you have 3+ logical states (guessed correctly, guessed incorrectly, guessed 42 for an easter egg), you will have to have another check.
Consider using a for loop instead of a while loop. while loops are good for when you do not need to know how many loops you've done, or when your loop criteria is a specific boolean expression. (ex while something.hasNext():)
for loops are good for a specific number of iterations, or when you need to access something sequentially. (there are also for each loops).
for i in range(MAX_GUESS): # i = 0 to i = MAX_GUESS -1
Then you won't need a check for your number of guesses since you're guaranteed to loop a max of MAX_GUESS times
A suggestion if I may. Get an IDE (integrated Development Environment) with syntax highlighting and checking. I use Eclipse with a python plugin, but eclipse is a bit much for beginners. Our CS professors suggested Wing, but I never used it
---
Finished product (aside from string formatting. I'll let you do that):
import random
import time
numOfGuesses = 0
numbertoguess = 0
MAX_GUESS = 10
guess = ''
playername = ''
playername = input ('What is your name:')
numbertoguess = random.randint (1, 100)
input("hello, " + playername + ", Guess the number I am thinking of \n(hint it's between 1 and 100")
for numOfGuesses in range(MAX_GUESS): # nOG = 0 to nOG = MAX_GUESS -1
guess = int(input("What is your guess:"))
time.sleep(1)
if guess < numbertoguess:
print ('Higher')
elif guess > numbertoguess:
print ('Lower')
else:
break;
if guess == numbertoguess:
print ("You are right," + playername + ",you guessed it in " + str(numOfGuesses) + "tries")
else:
print ("awe so close," + playername + ".")
print ("the number was" + str(numbertoguess) +".")
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
The code runs fine up to the point where it asks you if you want to keep playing. As of now, no matter what you type in it will go through the prompt again. I need it to run again if you type anything that starts with y, and break if anything else is typed
while(str(guess) == str(random_num)):
if(int(num_sum) <= int(1)):
print("You got it right in 1 guess!")
again = str(input("Would you like to play again? "))
print()
return prompt()
elif(int(num_sum) > int(1)):
print("you got it right in " + str(num_sum) + " guesses! ")
again = str(input("Would you like to play again? "))
return prompt()
if(str(again.startswith)("y") or ("Y")): #am I using the "startswith" feature wrong?
print()
return prompt()
else:
print("Overall Results")
break
def prompt():
constant_1 = 1
constant_2 = 100
random_num = (randint(constant_1, constant_2))
im_thinking = ("I'm thinking of a number between" +
(" ") + str(constant_1) + (" ") + ("and") + (" ") + str(constant_2) + ("..."))
print(im_thinking)
print(random_num)
guess = int(input("Your guess? "))
num_sum = 1
while((str(guess) != str(random_num))):
num_sum = num_sum + 1
if (str(guess) > str(random_num)):
print("It's lower.")
guess = int(input("Your guess? "))
elif (str(guess) < str(random_num)):
print("It's higher.")
guess = int(input("Your guess? "))
else:
guess = False
This question already has answers here:
TypeError: 'int' object is not callable
(10 answers)
Closed 6 years ago.
Ok, so, I'm trying to make a "guess the number" game, a game where you say a number and the other player say "Lower" or "Higher" depending on your answer, and when you guess the number correctly you win.
Maybe this was already answered, but I can't figure out what's wrong.
I don't get it, if inside the function you call itself, it is supposed to run itself again, right?
Not sure if it's helpful but I'm using Python 3.
number = 897
attempts = 0
def guess():
guess = input("Number: ")
guess = int(guess)
global attempts
if guess > number:
print("It's lower.")
attempts = attempts + 1
guess()
elif guess < number:
print("It's higher.")
attempts = attempts + 1
guess()
else:
print("Correct! The number was " + str(number) + "!")
print("It took you " + str(attempts) + "!"),
print("I'm thinking of a number, guess it!")
guess()
....
def guess(): # guess is a function
guess = input("Number: ")
guess = int(guess) # it's become int now
global attempts
if guess > number:
print("It's lower.")
attempts = attempts + 1
guess() # you're trying to call an int object, because you defined it as a int object as I said.
....
So please change your function name or that variable name.
Variable name is the same as function name. You've forgotten to add "attempts" at the correct guess string.
number = 897
attempts = 0
def guess1():
guess = input("Number: ")
guess = int(guess)
global attempts
if guess > number:
print("It's lower.")
attempts = attempts + 1
guess1()
elif guess < number:
print("It's higher.")
attempts = attempts + 1
guess1()
else:
print("Correct! The number was " + str(number) + "!")
print("It took you " + str(attempts) + " attempts !"),
print("I'm thinking of a number, guess it!")
guess1()