Reputation: 43
I was creating a guessing game for practice and this syntax error came up in my code which says that my break function is outside the loop. I looked at my code and it is not outside the loop so I would appreciate it if someone could help me with my problem.
from random import randint
def guessing_game():
print('Welcome to the Guessing Game')
print('If you would like to exit, just type exit')
while True:
num = randint(1,9)
guesses = []
while True:
try:
guess = int(input('Please guess a number between 1 and 9: '))
except:
print('Please enter a numerical value')
continue
else:
if guess < 1 or guess > 9:
print('OUT OF RANGE')
continue
else:
if guess == num:
print(f'Congratulations, you guessed the correct number in {len(guesses)} guesses')
break
else:
if guess > num:
print('TOO HIGH')
guesses.append(guess)
continue
else:
print('TOO LOW')
guesses.append(guess)
continue
play_again = input('Enter exit to stop playing: ')
if play_again == 'exit':
break
else:
continue
This is the error I get:
File "<ipython-input-1-09b3cd044357>", line 42
break
^
SyntaxError: 'break' outside loop
Upvotes: 2
Views: 1057
Reputation: 1064
Your line 42 is not in 2nd while loop
so that's why you getting an error make sure it will in while loop here is your line:
if play_again == 'exit':
break
else:
continue
you can copy this code:
from random import randint
def guessing_game():
print('Welcome to the Guessing Game')
print('If you would like to exit, just type exit')
while True:
num = randint(1,9)
guesses = []
while True:
try:
guess = int(input('Please guess a number between 1 and 9: '))
except:
print('Please enter a numerical value')
continue
else:
if guess < 1 or guess > 9:
print('OUT OF RANGE')
continue
else:
if guess == num:
print(f'Congratulations, you guessed the correct number in {len(guesses)} guesses')
break
else:
if guess > num:
print('TOO HIGH')
guesses.append(guess)
continue
else:
print('TOO LOW')
guesses.append(guess)
continue
play_again = input('Enter exit to stop playing: ')
if play_again == 'exit':
break
else:
continue
Upvotes: 0
Reputation: 27214
Check the indentation of the last few lines and make sure they're inside the
while
loop and it will work.
from random import randint
def guessing_game():
print('Welcome to the Guessing Game')
print('If you would like to exit, just type exit')
while True:
num = randint(1,9)
guesses = []
while True:
try:
guess = int(input('Please guess a number between 1 and 9: '))
except:
print('Please enter a numerical value')
continue
else:
if guess < 1 or guess > 9:
print('OUT OF RANGE')
continue
else:
if guess == num:
print(f'Congratulations, you guessed the correct number in {len(guesses)} guesses')
break
else:
if guess > num:
print('TOO HIGH')
guesses.append(guess)
continue
else:
print('TOO LOW')
guesses.append(guess)
continue
play_again = input('Enter exit to stop playing: ')
if play_again == 'exit':
break
else:
continue
Repl: https://repl.it/repls/TurbulentImpeccableObjectdatabase
Upvotes: 2