Skip to content Skip to sidebar Skip to footer

How Do I Make My Code Return Outside Loop? Could Someone Please Fix My Code?

I hope you are doing well! I am making a code for my free time. I just have a small issue with it. After you buy a sword in my game, I put 'break' so that it brings you to the else

Solution 1:

It looks like you are misunderstanding how if-else statements works. Since your print statements are inside the else statement they will only execute if the user had entered "yes" or "Yes". If you want the print statements to execute only if the user had entered anything else, this would work as expected.

However, if you simply want them to be run whenever they "leave" or don't enter the shop you can simply leave them outside any conditional, or even add a boolean value to make sure that they actually entered the shop beforehand:

shop_entered = False

if (response == "Yes") or (response == "yes"):
    shop_entered = True

    # do shop things...
        
if shop_entered:
  print("\033[1;37;40mYou exit the shop.")
  print("After leaving the shop, you head home.")

When you break your loop you are telling the program to stop the loop and execute the code following the loop; however, since there is no code following the loop, the if branch of the conditional is finished, and python will execute anything following the conditional (in this case anything that follows the else). Since there is no other code, your program exits without any more code being run.

If you add a print statement at then end or your script, something like print("thanks for playing!"), you will see "thanks for playing!" printed to the console after everything else is run.


Post a Comment for "How Do I Make My Code Return Outside Loop? Could Someone Please Fix My Code?"