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
Related
My issue is that python script ends when I get the number right, but doesn't print: You win!
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
#Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
I'm only 11, and just started programming a couple months ago, please help me!
Your code fails the first condition if a guess is correct:
while guess != number and tries > 0 :
If a guess is complete the loop will break after your else statement and never returns to the if condition checking for a guess.
Since you can't continue past the loop until a correct answer is inputted you could always write this as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
else :
guess = input('Try Again: ')
guess = float(guess)
print('You win!')
Bear in mind there's a bug in this that will cause you win to also be printed after the user runs out of guesses. I've decided to leave this here as I think it's easy to fix and would be good for you to resolve yourself to learn from. Feel free to write in the comments if you want me to do that for you however.
I would also recommend using code comments on your posts. In this case I would have presented the code for your question as follows:
import random
number = random.randint(1,100) # This part works fine
guess = input('Guess a number between 1 and 100: ') #Asks question
guess = float(guess)
tries = 10
while guess != number and tries > 0 :
if guess < number: # This part works fine
print('Too low')
tries = tries - 1
print('You have %s tries left' % (tries))
if guess > number:
print('Too high') # This part is also good
tries = tries - 1
print('You have %s tries left' % (tries))
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
continue
if guess == number :
print('You win!') # Why doesn't this work?
# Python ends at this line if I get it right, but doesn't print: You win!
else :
guess = input('Try Again: ')
guess = float(guess)
pass # WHILE*
When doing comparisons in your code, it is often best to try and only ask a particular question (do a comparison) once. Here I showed a way to restructure your two questions (correct guess & out of tries) to only do the questions once.
import random
number = random.randint(1, 100)
guess = input('Guess a number between 1 and 100: ') # Asks question
guess = float(guess)
tries = 10
while True:
tries -= 1
if guess < number:
print('Too low')
print('You have %s tries left' % (tries))
elif guess > number:
print('Too high')
print('You have %s tries left' % (tries))
else:
print('You win!')
break
if tries == 0:
print('You lose!')
print('The answer was ' + str(number))
break
guess = input('Try Again: ')
guess = float(guess)
I am making a python code that picks a random number and compares it to a guess made by the user.
import random
attempts=0
secret=random.randint(1,49)
print "welcome to my guessing game"
repeat
def repeat():
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts>6:
repeat()
but it is saying that repeat is not defined.
This will allow the user to guess 7 times, then prints game over:
this is for Python 2. for Python 3. use int(input(""))
import random
secret = random.randint(1,49)
attempts = 0
for attempts in range(7):
guess=input("I have thought of a number between 1 and 50. you have to try and guess it: ")
if secret==guess:
print "Well Done! you guessed it "
elif secret < guess:
print "too high"
guess=input(" Enter to have another go")
elif secret > guess:
print "too low"
guess=input("Enter to have another go")
if attempts == 6:
print "Game Over"
The Program is not working because you can not run or call a function before it is created. Also you should call repeat by doing this "repeat()"
I've adapted your code to the following which should work. You might want to read up on Local and Global Variables as that's what was causing your main issue in your code.
import random
def repeat(secret, attempts):
guess=raw_input("I have thought of a number between 1 and 50. you have to try and guess it")
if secret==guess:
print "Well Done! you guessed it in "+attempts+" attempts"
elif secret < guess:
print "too high"
guess=raw_input("have another go")
elif secret > guess:
print "too low"
guess=raw_input("have another go")
attempts += 1
while guess != secret and attempts < 6:
repeat(secret, attempts)
attempts = 0
secret = random.randint(1,49)
print "welcome to my guessing game"
repeat(secret, attempts)
my apologies if I'm asking a silly question, but I'm a bit confused...
I've been doing the MIT6.00X course at edx and one of the exercises is to use bisection search algorithm to find the secret number. It took me about 4 hours to finish the exercise (Yeah I'm a noob) but I managed to build this code:
numGuesses = 0
lo = 0
hi = 100
mid = (hi + lo)/2
num = raw_input( "Input a number between 0 and 100 ")
if num > 0 or num < 100:
while mid != num:
print ("Is your number " + str(mid) + "?")
userinput = raw_input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")
else:
print ("You should use a number between 0 and 100")
While testing it by hand it works just fine, although in the exercise there are a few questions that don't go through mainly because the site instead of keep guessing if it's higher or lower sometimes it presses the wrong key and I fail the exercise.
After trying to change the code I wasn't able to finish the course so I've seen the answer, and this is were I did wrong, I should had use a boolean to keep the code flowing until it finds the correct number.
My question is: Is my code that wrong? Also is there any mistake I did that's preventing the site to press the correct letter? Just curious
Many thanks
this is one of the MITx finger exercise that I just finally solved it today. here is my method:
print('Please think of an integers BETWEEN 0 and 100!')
#Define variable
x=100
low=0
high=x
ans=0
#Guessing code part
while ans<=x:
print'Is your secret number:', str((low+high)/2), '?'
s=raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly:")
if s!='h' and s!='l' and s!='c':
print'Sorry I did not understand your input.'
elif s=='h':
high=(low+high)/2
elif s=='l':
low=(low+high)/2
elif s=='c':
print'Game over. Your secret number is:', str((low+high)/2)
break
lo = 0
hi = 100
mid = (hi + lo)/2
print 'Please think of a number between 0 and 100!'
while True:
print ("Is your number " + str(mid) + "?")
userinput = raw_input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")
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
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. ;)