Ad

Calling A Function With An If Statement And A While Loop

- 1 answer

I'm trying to make a pick your own adventure game in python and I was using a while loop to make sure that you can only pick two answers. Everything works except when the if statement gets what it was looking for then, instead of calling the function, it just ends the while loop.

choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()

def jungle_1():
  print(" You head into the the unruly jungle to find cover and come across a small \n cave that looks to be empty.\n This would be a perfect spot to setup camp.\n\n In order to get to the cave you have to cross a river.")

def coast_1():
  print(" You wander the coast, your skin still aching,   looking for any sign of \n wreckage. \n\n it's been 3 hours, you don't find anything.")


while choice_1_lower != "jungle" and choice_1_lower != "coast":
  
  if choice_1_lower == "jungle":
    jungle_1()
  elif choice_1_lower == "coast":
    coast_1()
  elif choice_1_lower != "jungle" and choice_1 != "coast":
    print(f" This is not a choice. {choice_1}")
    choice_1_lower = None
    choice_1 = input("\n jungle or coast? ")
    choice_1_lower = choice_1.lower()

I've been brainstorming and I don't have any idea how to keep the function of the while loop while also keeping the function of the if statement.

Ad

Answer

The issue with your code is, that when entering jungle or coast the while loop is not entered at all.

One option would be to run the while loop 'forever' and use the break statement once you want to leave the loop.

choice_1 = input("\n jungle or coast? ")
choice_1_lower = choice_1.lower()

def jungle_1():
  print(" You head into the the unruly jungle to find cover and come across a small \n cave that looks to be empty.\n This would be a perfect spot to setup camp.\n\n In order to get to the cave you have to cross a river.")

def coast_1():
  print(" You wander the coast, your skin still aching,   looking for any sign of \n wreckage. \n\n it's been 3 hours, you don't find anything.")


while True:
  if choice_1_lower == "jungle":
    jungle_1()
    break
  elif choice_1_lower == "coast":
    coast_1()
    break
  elif choice_1_lower != "jungle" and choice_1 != "coast":
    print(f" This is not a choice. {choice_1}")
    choice_1_lower = None
    choice_1 = input("\n jungle or coast? ")
    choice_1_lower = choice_1.lower()

Ad
source: stackoverflow.com
Ad