I am just learning python and I wrote this, but I want to show all the guesses and maybe whether they are too high or low. The "responseList" part is where I need help. Thanks!
import random, easygui
secret = random.randint (1, 100)
guess = 0
tries = 0
easygui.msgbox ("""Guess the secret number.
It is from 1 to 99. You have five tries. Get Guessin' !""")
while guess != secret and tries < 5:
user_response = guess = easygui.integerbox ("C'mon...GUESS!!! ")
if not guess: break
if guess <= (secret + 5) and guess > secret:
easygui.msgbox(str(guess) + " is too HIGH... but you're close!")
if guess >= (secret - 5) and guess < secret:
easygui.msgbox(str(guess) + " is too LOW... but you're close!")
if guess < (secret - 5):
easygui.msgbox(str(guess) + " is too LOW... Guess higher")
if guess > (secret + 5):
easygui.msgbox (str(guess) + " is too HIGH...Guess lower")
tries = tries + 1
responseList = [user_response]
easygui.msgbox (responseList)
if guess == secret:
easygui.msgbox ("Darn! You got it!")
else:
easygui.msgbox ("Ha, Ha, Ha! No more guesses! To the firin' squad with ya!")
easygui.msgbox (str(secret) + " was the secret number")
I'm guessing you want responseList to contain a list of all user's responses. You didn't write it. :)
You'll need to set responseList to empty list on the start and than append each new response to it.
responseList = [user_response] just sets it to one-element list every time. Obviously you'll end up with a one-element list with just the last response.
Initialize responseList before the while guess != secret and tries < 5: loop. In the loop, you can append tuples to responseList containing the guess, and if it was too high or low (use a variable, say where, to store the value 'HIGH' or 'LOW'). Then outside the while loop, show the formatted results, with easygui.msgbox:
responseList = []
while guess...:
user_response = ...
if not...
if guess <=...
where = 'HIGH'
if guess >=...
where = 'LOW'
if guess <...
where = 'LOW'
if guess >...
where = 'HIGH'
tries...
responseList.append((guess, where))
responseString = ', '.join([ '%d (%s)' % (guess, where)
for guess, where in responseList])
easygui.msgbox(responseString)
that line with the responseString is a List Comprehension, which you can read up on, or ask about here.
EasyGUI is not part of the standard Python distribution. You can download it from SourceForge here http://easygui.sourceforge.net/. It installed into a Python(x,y) installation on the first try with only "setup.py install". To get your list to behave as you expect, try this version:
import random, easygui
secret = random.randint (1, 100)
guess = 0
tries = 0
easygui.msgbox ("""Guess the secret number.
It is from 1 to 99. You have five tries. Get Guessin' !""")
responseList = []
while guess != secret and tries < 5:
user_response = guess = easygui.integerbox ("C'mon...GUESS!!! ")
if not guess: break
if guess <= (secret + 5) and guess > secret:
easygui.msgbox(str(guess) + " is too HIGH... but you're close!")
if guess >= (secret - 5) and guess < secret:
easygui.msgbox(str(guess) + " is too LOW... but you're close!")
if guess < (secret - 5):
easygui.msgbox(str(guess) + " is too LOW... Guess higher")
if guess > (secret + 5):
easygui.msgbox (str(guess) + " is too HIGH...Guess lower")
tries = tries + 1
responseList.append(user_response)
easygui.msgbox (",".join(["%d"%x for x in responseList]))
if guess == secret:
easygui.msgbox ("Darn! You got it!")
else:
easygui.msgbox ("Ha, Ha, Ha! No more guesses! To the firin' squad with ya!")
easygui.msgbox (str(secret) + " was the secret number")
initialize responseList as a list outside the loop, then append each number to it as you go. I added some commas to separate your numbers in the msgbox for a bonus. ;)
Related
So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results to automatically go to the list when the game is completed and then to be able to print the list when desired.
I'm not sure if I need to create a new function for this, or if I should be creating this within my current "guessing_game" function. I've tried to create a list previously, but I'm not sure how to create and store the variable of the game result in order to add it into the list. I feel like this is probably a fairly simple problem, so I apologize if this is a dumb question.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name ")
number_of_guesses = 0
print('Howdy' + player_name + "Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(guessing_game())
You can create a list inside of the function, and then everytime they guess, you can store the guess inside the list. At the end, we can print the list.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name: ")
number_of_guesses = 0
guesses = []
print('Howdy ' + player_name + " Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
guesses.append(guess)
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print("These were the numbers you guessed:")
for g in guesses:
print(g)
print(guessing_game())
What you need to do is create a list with something like val = []. I added it into the code and also added a formatting piece so it looks nice.
def guessing_game():
import random
guesses = []
number = random.randint(1, 1000)
guess = number / 2
player_name = input("Enter name ")
number_of_guesses = 0
print(f'Howdy {player_name}. Guess a number between 1 and 1000: ')
while number_of_guesses < 10:
guess = int(input('> '))
guesses = guesses + [guess]
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
formatted_guesses = ''
for _ in range(len(guesses)):
if _ != len(guesses) - 1:
formatted_guesses = formatted_guesses + str(guesses[_]) + ', '
else:
formatted_guesses = formatted_guesses + str(guesses[_]) + '.'
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
print(f'You guessed {formatted_guesses}')
else:
print("Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(f'You guessed {formatted_guesses}')
guessing_game()
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.
I keep getting this error for the second break command, not the first. Why is this happening?
It says:
SyntaxError: 'break' outside loop
Here is my code:
import random
import easygui
secrets = random.randint(1, 200)
secret = random.randint(1, 100)
guess = 0
tries = 0
easygui.msgbox("""AHOY! I'm the Dreaded Pirate Roberts, and I have a secret! It is a number from 1 to 99. I'll give you 10 tries.""")
while guess != secret and tries < 10:
guess = easygui.integerbox("What's yer guess, matey?")
if not guess: break
if guess < secret:
easygui.msgbox(str(guess) + " is too low, ye scurvy dog!")
elif guess > secret:
easygui.msgbox(str(guess) + " is too high, landlubber!")
tries = tries + 1
if guess == secret:
easygui.msgbox("Avast! Ye got it! My secret is: **** ** ****! NO MATTER WHAT ****** SAYS, **** *****!!!!!!!!!!!!!!!!!")
else:
easygui.msgbox("No more guesses! Better luck next time, matey!")
easygui.msgbox("Now, since ye lost, ye can try 1-50.")
while guess != secrets and tries < 15:
guess = easygui.integerbox("What's yer guess, matey?")
if not guess: break
if guess < secrets:
easygui.msgbox(str(guess) + " is too low, ye scurvy dog!")
elif guess > secrets:
easygui.msgbox(str(guess) + " is too high, landlubber!")
tries = tries + 1
The second "if not guess: break" is what the error is about.
Can somebody explain?
Read the error description:
>>> if True: break
SyntaxError: 'break' outside loop
Make sure that you indent that entire section of code such that it is part of the while loop
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)
This is an example in the Python book I'm reading. When I try to run the program there's an error, and when I check the code for the error elif is highlighted in red. I'm programming in Python 2.5.
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret and tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
if guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
Python is indentation sensitive.
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret and tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
elif guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
Edit: I know there are still bugs in this, such as tries = tries + 1 which should be somewhere else in the code. But this version at least does not give syntax errors.
The problem lies in your indentation.
Instead of:
if foo:
foobar()
elif bar:
barbaz()
It should be:
if foo:
foobar()
elif bar:
barbaz()
Fixed, your code would then look like this (note, I've also fixed your else at the end to work correctly):
import random
secret = random.randint(1, 99)
guess = 0
tries = 0
print "It is a number between 1 and 99. I'll give you six tries. "
while guess != secret:
if tries < 6:
guess = input("What's your guess? ")
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
elif guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret
break
There are several problems with this code.
The elif and if should have the same indentation level.
You only increment tries in the too-high case.
input() returns a string; you should convert it to an integer.
After testing < and >, the == is redundant.
Since <, > and == cover every case, you'll never reach the else:
Here's a reworking of the logic:
while guess != secret and tries < 6:
guess = int(input("What's your guess? "))
if guess < secret:
print "Too low!"
elif guess > secret:
print "Too high"
tries = tries + 1
if guess == secret:
print "Correct! You found my secret!"
else:
print "No more guesses! Better luck next time!"
print "The secret number was", secret