Home > Back-end >  How to stop a code from executing after a specific point in python?
How to stop a code from executing after a specific point in python?

Time:05-20

I am just starting out in learning python and I was trying to create a word guessing game where I have a secret word and the user has 3 attempts to guess it.

I basically finished the game but am stuck on one part of it.

Whenever I run my code, and guess the word in the first try, the terminal prints two successful print statements. For example, on line 12, I code that if the user guesses the word then print "Good Job, You win!"but whenever I guess the word in first try it also prints "You have just won" on line 24 (I coded this line so if the user guesses the word after 1st try it should print this).

SO, is there a way where I can end the code after line 12 if the condition is met?? so it does not print both messages on line 12 and 24 if guessed right in the first try.

please help this beginner noob out. Thanks!

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")

CodePudding user response:

You could call the built-in quit() function. If/when you modularize your code into functions, this could be done with a return call.

The quit() function will basically tell the program to immediately end and will not execute the rest of the code.

CodePudding user response:

You can import sys and use sys.exit()

Some other ways

  • Related