我在 while 循环中有一个 if 函数,但它要么忽略它,要么不中断
Posted
技术标签:
【中文标题】我在 while 循环中有一个 if 函数,但它要么忽略它,要么不中断【英文标题】:I have an if function in a while loop, but it either ignores it or doesn't break 【发布时间】:2019-05-14 04:21:21 【问题描述】:while True:
print("We have entered in the open sea, but the current is pushing us.
We can veer left and"
+"\nmiss the storm, or go straight through it. Type [left] or
[straight] exactly as it is in the box.")
turnChoice = input()
if turnChoice == "left":
food = food - 2
time.sleep(2)
print("You missed the storm, but you lost a little food. Your
current
food level is 5. If you let it go to zero, "
+"\nyour health will decrease.")
break
if turnChoice == "straight":
time.sleep(2)
random.randint(1,5)
break
if random == 1:
food = food - 2
print("You tried to go through the storm, but the ship was damaged.
You lost some food.")
break
if random == 2:
print("The ship made it through the storm without taking damage
somehow.
You did not loose any supplies or health.")
break
if random == 3:
print("The ship made it through. It made a lot of noise, but no
supplies were lost.")
break
if random == 4:
health = health - 20
print("The ship made it through, but there was damage. While you
were inside the ship, a stack of barrels fell on you."
+"\n You took some damage, receiving a concussion and fracturing
your arm. But you will live.")
break
if random == 5:
water = water - 2
print("You made it through the storm, but some water barrels were
lost to the storm. ")
time.sleep(2)
print("Here is your water status, don't let it get to zero: ")
print(water)
break
if turnChoice not in("left", "straight"):
print("Invalid input, please try again.")
对不起,如果它的格式不好,我是 *** 的新手。我正在为我的英语项目编写一个文字游戏。我试图在“while”循环中运行这些不同的“if”函数,但它要么忽略它们,要么只是循环整个函数。如果您选择“直接”,那么它应该拉一个随机数生成器并选择一个随机场景。如果你选择“左”,它只会减少你的食物。 “left”功能有效,但“straight”无效。另外,我试图让它在它通过“左”功能或“直”功能后打破,但由于“如果”功能,我不知道如何去做。这是在Pycharm上编程的,我相信是python 3.7.0。
【问题讨论】:
就我而言,它适用于 left 和 straight。当你选择直接时,它会选择什么? 我将尝试通过提问来提供帮助。break
是做什么的?
【参考方案1】:
两件事:
Break 用于退出 while 循环。对于 python,if 语句将根据缩进退出。因此,要直奔并继续您的场景,您只需在直奔后移除休息时间。
random.randint 为您提供介于 1 和 5 之间的随机整数,但不会将其保存在您用于检查场景的变量中。所以你需要随机存储它。 “随机”。部分只是从您导入的随机模块中获取此功能。
当他们输入 straight 并正确分配 random 时,这将退出 if 语句而不是 while 循环。这两个更改为我修复了它。
if turnChoice == "straight":
time.sleep(2)
random = random.randint(1,5)
if random == 1: #rest of code
【讨论】:
【参考方案2】:您的 random.randint(1,5)
行没有分配给变量,因此没有任何 if 语句被触发。尝试做类似的事情
rnd = random.randint(1,5)
if rnd == 1:
# stuff here
if rnd == 2:
# stuff here
【讨论】:
以上是关于我在 while 循环中有一个 if 函数,但它要么忽略它,要么不中断的主要内容,如果未能解决你的问题,请参考以下文章