使用 if 语句和 while 循环调用函数

calling a function with an if statement and a while loop

我正在尝试在 python 中选择您自己的冒险游戏,我使用 while loop 来确保您只能选择两个答案。一切正常,除非 if 语句得到它正在寻找的内容,而不是调用函数,它只是结束 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()

我一直在集思广益,我不知道如何在保持 while loop 的功能的同时还保持 if 语句的功能。

你的代码的问题是,当进入丛林或海岸时,根本没有进入 while 循环。

一个选择是 运行 while 循环 'forever' 并在您想离开循环时使用 break 语句。

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