如何在python中阻止代码在特定点后执行?



我刚刚开始学习python,我试图创建一个猜字游戏,我有一个秘密单词,用户有3次尝试猜它。

我基本上完成了游戏,但我在其中的一个部分卡住了。

每当我运行代码并在第一次尝试中猜出单词时,终端都会打印两个成功的print语句。例如,在第12行,我编写了这样的代码:如果用户猜出了单词,那么打印"Good Job, You win!",但是每当我第一次猜出单词时,它也打印"You have just won";在第24行(我对这行进行了编码,所以如果用户在第一次尝试后猜出了单词,它应该打印这个)。

所以,有一种方法,我可以结束代码后的第12行,如果条件得到满足吗?因此,如果在第一次尝试中猜对了,它不会打印第12行和第24行上的消息。

请帮助这个初学者。谢谢!

secret_word = "Tiger"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
print("Hello, welcome to the guessing game!")
x = input("Please guess the secret word: ")
if x == secret_word:
print("Good Job, You win!")
#end the code here and not run anything after if user guesses the right word
while guess != secret_word and x != secret_word and not(out_of_guesses):
if guess_count < guess_limit: 
guess = input("Wrong, enter your guess word again: ")
guess_count = guess_count + 1
else:
out_of_guesses = True

if out_of_guesses:
print("Sorry, You have run out of guesses.")
else:
print("You have just won")

可以调用内置的quit()函数。如果/当你将代码模块化为函数时,这可以通过return调用来完成。

quit()函数基本上会告诉程序立即结束,而不会执行其余的代码。

您可以导入sys并使用sys.exit()

其他方法

最新更新