How to stop a condition for yes or no (SOLVED)

Question:

I’m making a simple higher or lower number guessing game that asks the user if they "want to play a game? Yes or No." Then either continues with the game or stops completely after printing "Okay. Maybe next time." (I’ve already imported a random number for it.)

The issue that I have is that after creating my conditional for when the user says ‘No’, it does print "maybe next time" but also continues with the game. I’m not sure how to solve this. I’ll leave an example of the code below.

I’ve tried to make it a loop but then it just asks the "Would you like to play a game? Yes or No " Again until the user says no. How can I stop running the code after "Maybe next time" so that my next line of code doesn’t show afterwards?

play_game = input("Would you like to play a game? Type Yes or No : ")

if play_game == "Yes":
  print("Great! Let's begin.")
elif play_game == "No":
  print("Okay. Maybe next time.")
else:
  print("Error >:( 'Yes' or 'No' only please!")

print(random_number)
user_guess = input("Higher or lower? Type 'H' for Higher and 'L' for lower.")

if user_guess == 'H':
  print("You think it'll be higher? Let's see!")
elif user_guess == 'L':
  print("You think it'll be lower? Let's see!")
else:
  print('Error >:0... Please only type H or L')
Asked By: kerropileaaf

||

Answers:

You could make your program exit when the user declines to play. You could do this by using the exit() function from the sys module:

import sys

if play_game == "Yes":
  print("Great! Let's begin.")
elif play_game == "No":
  print("Okay. Maybe next time.")
  sys.exit()
Answered By: Minion3665

in loop you can use break to exit from the loop, like this:

while True:
    play_game = input("Would you like to play a game? Type Yes or No : ")

    if play_game == "Yes":
        print("Great! Let's begin.")
    elif play_game == "No":
        print("Okay. Maybe next time.")
        break
    else:
        print("Error >:( 'Yes' or 'No' only please!")
        raise 'error'