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) +".")
Related
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!")
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.
This is a game I am currently trying to make. I am coding this game in python 3.4. it doesn't run.
# this is a guess the number game!
import random
guesses = 0
name = input("what is your name?")
number = random.randint(1, 20)
print = name + ", I am thinking of a number between 1 and 20..."
while guesses << 7:
guess = int(raw_input("Take a guess."))
guesses = guesses + 1
if guess < number:
print ("your guess is too low!")
if guess > number:
print ("your guess is too high!")
if guess == number:
break
if guess == number:
guesses = str(guesses)
print ("Good job," + name + "you guessed my number in" +guesses +"guesses!")
if guess != number:
number = str(number)
print ("Nah dude, better luck next time!")
I think you meant to use < instead of <<. << and >> are bit shift operators to the left and right respectively.
Your last two if conditions are also outside your loop, and don't make much sense. You're already checking if guess == number once and breaking if that condition is met. if guess != number your already checking this by using < and > respectively.
print = ...? print syntax is print(some_stuff, ...). Indentation is also off at the top, but assuming that's just due to posting your first question.
Also, raw_input is for python2 it's just input in python3. You could clean the print statements up some with % formatters or using .format.
Fixed code: (Python 3 version since that's whats tagged in the question...)
import random
name = input("what is your name?")
number = random.randint(1, 20)
#print("%s I am thinking of a number between 1 and 20..." % name)
print(name + " I am thinking of a number between 1 and 20...")
guesses = 0
while guesses < 7:
guess = int(input("Take a guess."))
guesses += 1
if guess < number:
print ("your guess is too low!")
elif guess > number:
print ("your guess is too high!")
else:
#print("Good job %s you guessed my number in %d guesses" % (name, guesses))
print ("Good job, " + name + " you guessed my number in " + str(guesses) + " guesses!")
break
There are many errors in your program. Always include errors you get in your question. Given the syntax error you are making first get your hands dirty on python interpreter by executing simple commands. Below should help. Below is in Python 2, for Python 3 replace, raw_input() with input and print 'something' with print ('something')
1st Solution:
import random
name = raw_input("Hello! What is your name?\n")
print "Well, " + name + ", I am thinking of a number between 1 and 20"
no = random.randint(1,20)
guess = int(raw_input("Take a guess\n"))
count =1
while guess != no:
if guess < no:
print "Your guess is too low."
if guess > no:
print "Your guess is too high"
count +=1
guess = int(raw_input("Take a guess\n"))
print "Good job, %s! You guessed my number in %d guesses!" % (name ,count)
2nd Solution:
import random
def check():
global count # good example of use of global
guess = int(raw_input("Take a guess\n"))
if guess == no:
print "Good job, %s! You guessed my number in %d guesses!" %(name,count)
elif guess < no:
print "Your guess is too low."
count +=1
check()
else:
print "Your guess is too high"
count +=1
check()
name = raw_input("Hello! What is your name?\n")
print "Well, " + name + ", I am thinking of a number between 1 and 20"
no = random.randint(1,20)
global count
count =1
check()
Your code goes good, little changes can make it run!
import random
guesses = 0
name = raw_input("what is your name?") # use input() is using Python 3
number = random.randint(1, 20)
print name + ", I am thinking of a number between 1 and 20..."
while guesses < 7:
guess = int(raw_input("Take a guess."))
guesses = guesses + 1
if guess < number:
print ("your guess is too low!")
if guess > number:
print ("your guess is too high!")
if guess == number:
break
if guesses == number:
print ("Good job,", name, "you guessed my number in", guesses, "guesses!")
if guesses != number:
number = str(number)
print ("Nah dude, better luck next time!", "The number is", number)
I've looked up several of these questions and can't seem to apply it to my code correctly. I'm definitely new to Python and developed a number guessing game for practice. The last error handling I need is to make sure that anything typed that is not an integer, will return an error message. I was hoping to use an "if" statement like I have for other conditions, but will work with what I can get. Thanks!
(this is just a snippet. i didn't include the entire program)
def gamestart():
print(rndnumber)
for GuessAmount in range (1,11):
ActualGuess = int(input("Guess number " + str(GuessAmount) + ": "))
if ActualGuess < rndnumber:
print("HIGHER!")
if ActualGuess > rndnumber:
print("LOWER!")
if ActualGuess != rndnumber:
GuessAmount == GuessAmount + 1
if ActualGuess == rndnumber:
print("You Win!")
gameend()
print("")
print("Sorry, but you ran out of guesses.")
print("")
gameend()
Use try/except:
while True:
guess = input("Guess number " + str(GuessAmount) + ": ")
try:
guess_int = int(guess)
break
except ValueError:
print "please enter only integers"
Now you have your (converted to integer) input in guess_int.
If it was impossible to convert the input to integer, user gets warning and enters number once again.