gpt4 book ai didi

python - 如何修复游戏中的语法错误?

转载 作者:太空宇宙 更新时间:2023-11-04 01:52:54 24 4
gpt4 key购买 nike

我正在创建一个用于练习的猜谜游戏,我的代码中出现了这个语法错误,它说我的 break 函数在循环之外。我查看了我的代码,它不在循环之外,所以如果有人能帮助我解决我的问题,我将不胜感激。

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

这是我得到的错误:

  File "<ipython-input-1-09b3cd044357>", line 42
break
^
SyntaxError: 'break' outside loop

最佳答案

检查最后几行的缩进,确保它们在while 循环,它将起作用。

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

回复:https://repl.it/repls/TurbulentImpeccableObjectdatabase

关于python - 如何修复游戏中的语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57584287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com