如何重复执行代码并在if/else语句中使用while循环?

huangapple go评论61阅读模式
英文:

How do I repeat a code and use while loop in an if/else statement?

问题

else: # 这里我想要在这个else语句中使用while循环,就像其中的代码一样。
    print("你掉进了一个洞里!游戏结束!")
    while True:
        main()
        retry = input("你想再试一次吗?") # 当代码为假时,它不会在这个else语句和while循环中打印任何内容!
        if retry == "no": # 我该如何修复这段代码?
            break
英文:

I want to repeat a whole code in an else statement using while loops. I already tried the following, it does not work and when the code is false it does not print anything in the else statement and while loop!. How do I fix this?

# Start()
import sys
def main():

    print('''
    *******************************************************************************
            |                   |                  |                     |
    _________|________________.=""_;=.______________|_____________________|_______
    |                   |  ,-"_,=""     `"=.|                  |
    |___________________|__"=._o`"-._        `"=.______________|___________________
            |                `"=._o`"=._      _`"=._                     |
    _________|_____________________:=._o "=._."_.-="'"=.__________________|_______
    |                   |    __.--" , ; `"=._o." ,-"""-._ ".   |
    |___________________|_._"  ,. .` ` `` ,  `"-._"-._   ". '__|___________________
            |           |o`"=._` , "` `; .". ,  "-._"-._; ;              |
    _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
    |                   | |o;    `"-.o`"=._``  '` " ,__.--o;   |
    |___________________|_| ;     (#) `-.o `"=.`_.--"_o.-; ;___|___________________
    ____/______/______/___|o;._    "      `".o|o_.--"    ;o;____/______/______/____
    /______/______/______/_"=._o--._        ; | ;        ; ;/______/______/______/_
    ____/______/______/______/__"=._o--._   ;o|o;     _._;o;____/______/______/____
    /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
    ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
    /______/______/______/______/______/______/______/______/______/______/_____ /
    *******************************************************************************
    ''')
    print("Welcome to the Programming Universe!.")
    print("Your mission is to get all the 10 laptops for programming.\n") 

    #Write your code below this line 👇
    direction = input("There are two directions right or left?: ").lower()
    if direction == "right":
        swim_or_wait = input("Do you want to wait or swim?: ").lower()
        if swim_or_wait == "wait":
            option = input("\nWhich language is the easiest? [1]Python, [2]C++, [3]C#, [4]Lua, [5]JS: ").lower()
            if option == "python" or option == "1":
                print("You got all the 10 laptops for programming! You Win")
            else:
                print("\nYou get trapped! Game over!")
        else:
            print("You were attacked by evil robots! Game Over!")
    else: # Here I want the while loop in this else statement like the code in it.
        print("You fall into a hole! Game Over!")
        while True:
            main()
            retry = input("Do you want to try again?") # When the code is false it does not print anything in this else statement and while loop!
            if retry == "no": # How do I fix this code?
                break


I tried using while loop like this. Also this is the part of the code that is not executing due to the while loop.

 else: # Here I want the while loop in this else statement like the code in it.
        print("You fall into a hole! Game Over!")
        while True:
            main()
            retry = input("Do you want to try again?") # When the code is false it does not print anything in this else statement and while loop!
            if retry == "no": # How do I fix this code?
                break

答案1

得分: 0

它有效,只需从内部移除 while 循环

def main(): ...

while True:
    main()
    retry = input("Do you want to try again?")  # 当代码是
    if retry == "no":
        break
英文:

It works just take out the while loop from inside

    def main(): ...
while True:
main()
retry = input("Do you want to try again?") # When the code is     
if retry == "no": 
break

答案2

得分: 0

我不明白为什么要使用while循环来做这个。我认为你想要做的是打印“游戏结束”,然后询问“你想再试一次吗?”如果答案不是“no”,则通过调用main()函数来重复游戏。你不需要使用while循环来实现这个:

    else:
        print("你掉进了一个坑!游戏结束!")
        retry = input("你想要再试一次吗?")
        if retry == "no":
            exit()  # 退出游戏
        main()  # 重置游戏

通过使用这种递归结构,你的游戏可以无限地运行,而无需使用while循环。

英文:

I don't understand why you would use a while loop for this. What I think you want to do is printing Game Over, then asking "Do you want to try again?" and if the answer is anything but "no", repeat the game by calling the main() function. You don't need a while loop for this:

    else:
        print("You fall into a hole! Game Over!")
        retry = input("Do you want to try again?")
        if retry == "no":
            exit()  # Exit the Game
        main()  # Reset the Game

By using this recursive structure, your game can run endlessly without a while loop.

答案3

得分: 0

这是你提供的代码的翻译部分:

问题有点混淆,但我认为你想要解决以下问题:

  1. 只有在进入最后的else语句时才会打印宝藏箱,
  2. 只有在最后的else语句为真时才会执行while循环,
  3. 如果用户说“yes”,则无法退出while循环。
    (如果只想看解决方案,请滚动到底部。)

要解决问题1,只需在函数调用后立即调用main(),并删除while循环内部的main()函数调用(除非你希望将其保留)。

要解决问题2,添加一个名为game_over的变量,并在代码开头设置为False(在import sys之后,我看不到你在哪里使用它,所以请检查import语句的用法)。然后,在以下位置末尾:

else:
print("You get trapped! Game over!")

以及:

else:
print("You were attacked by evil robots! Game Over!")

你可以添加:

game_over = True

对于以下情况也可以做同样的处理:

else:
print("You fell into a hole! Game Over!")

但请删除while循环。而是将其移出所有内容,并将while循环放在条件语句内部:

if game_over:  # 这段代码不是最终版。稍后仍会更改。
while True:
main()  # 如果需要的话。
retry = input("Do you want to try again?")
if retry == "no":
break

要解决问题3,只需将while循环移到最外部的缩进位置(即不缩进)。这样,任何不是'no'的输入都将被解释为'yes',并重新开始游戏。

这是最终的代码:

import sys


def main():  # 对于糟糕的缩进,抱歉,无法解决

    print('''
*******************************************************************************
        |                   |                  |                     |
________|________________.=""_;=.______________|_____________________|_______
|                   |  ,-"_,="           "=._,  |                  |
|___________________|__"=._o`"-._        `"=._|___________________|
        |                "=._o`"=._      _`=._                     |
________|_____________________:=._o "=._."_.-="'"=.__________________|_______
|                   |    __.--" , ; `"=._o." ,-""-. _". |
|___________________|_._" ,. .` ` `` , ` "-._"-._". '__.|___________________
        |           |o`"=._` , "` `; .". ,  "-._"-._ ;              |
________|___________| ;`-.o`"=._; ."` ` " ,__.--o;   |
____/______/______/___|o;._    "      `.o|o_.--"    ;o;____/______/______/____
/______/______/______/"=.o|o_.--""___/______/______/______/______/______/____
____/______/______/______/__"=._o_.--"____/______/______/______/______/____
/______/______/______/______/____"=._o._; |_.--"o.--"_/______/______/______/
____/______/______/______/______/_______"=."_.-"_.-"____/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
game_over = False
while True:
    main()
    print("Welcome to the Programming Universe!")
    print("Your mission is to get all the 10 laptops for programming.\n")
    direction = input("There are two directions right or left?: ").lower()
    if direction == "right":
        swim_or_wait = input("Do you want to wait or swim?: ").lower()
        if swim_or_wait == "wait":
            option = input("\nWhich language is the easiest? [1]Python, [2]C++, [3]C#, [4]Lua, [5]JS: ").lower()
            if option == "python" or option == "1":
                print("You got all the 10 laptops for programming! You Win")
            else:
                print("\nYou get trapped! Game over!")
                game_over = True
        else:
            print("You were attacked by evil robots! Game Over!")
            game_over = True
    else:
        print("You fall into a hole! Game Over!")
        game_over = True
    if game_over:
        main()  # 如果需要的话。
        retry = input("Do you want to try again?")
        if retry == "no":
            break
英文:

The question is a little bit confusing, but I think you want to fix the fact that:

1) The treasure box only prints if you enter the last else statement,
2) the while loop only executes if the last else statement is true, and
3) you cannot get out of the while loop if the user says 'yes'.
(Scroll to the bottom if you just want to see the solution.)

To fix Problem 1, just call main() right after the function is called, and delete the main() function call inside the while loop (unless you want it there.)

To fix Problem 2, add a variable game_over and set it to False at the beginning of the code, after import sys (I don't see where you use that, so check the usages of the import statement.) Then, to the end of:

else:
print("\nYou get trapped! Game over!")

And:

else:
print("You were attacked by evil robots! Game Over!")

You can add:

game_over = True

You can do the same for:

else:
print("You fell into a hole! Game Over!")

But, delete the while loop. Instead, move it out of everything, and put the while loop inside a conditional:

if game_over:  # This code is not final. It will still be changed later.
while True:
main()  # If you want.
retry = input("Do you want to try again?")
if retry == "no":
break

To fix Problem 3, simply move the while loop to the outermost indentation (i.e. no indent). This way, any input that is not 'no' will be interpreted as 'yes' and start the game again.

# This is the final code:
import sys
def main():  # Sorry for bad indentation, couldn't fix it somehow
print('''
*******************************************************************************
|                   |                  |                     |
_________|________________.=""_;=.______________|_____________________|_______
|                   |  ,-"_,=""     `"=.|                  |
|___________________|__"=._o`"-._        `"=.______________|___________________
|                `"=._o`"=._      _`"=._                     |
_________|_____________________:=._o "=._."_.-="'"=.__________________|_______
|                   |    __.--" , ; `"=._o." ,-"""-._ ".   |
|___________________|_._"  ,. .` ` `` ,  `"-._"-._   ". '__|___________________
|           |o`"=._` , "` `; .". ,  "-._"-._; ;              |
_________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
|                   | |o;    `"-.o`"=._``  '` " ,__.--o;   |
|___________________|_| ;     (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._    "      `".o|o_.--"    ;o;____/______/______/____
/______/______/______/_"=._o--._        ; | ;        ; ;/______/______/______/_
____/______/______/______/__"=._o--._   ;o|o;     _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
game_over = False
while True:
main()
print("Welcome to the Programming Universe!.")
print("Your mission is to get all the 10 laptops for programming.\n") 
direction = input("There are two directions right or left?: ").lower()
if direction == "right":
swim_or_wait = input("Do you want to wait or swim?: ").lower()
if swim_or_wait == "wait":
option = input("\nWhich language is the easiest? [1]Python, [2]C++, [3]C#, [4]Lua, [5]JS: ").lower()
if option == "python" or option == "1":
print("You got all the 10 laptops for programming! You Win")
else:
print("\nYou get trapped! Game over!")
game_over = True
else:
print("You were attacked by evil robots! Game Over!")
game_over = True
else:
print("You fall into a hole! Game Over!")
game_over = True
if game_over:
main()  # If you need it.
retry = input("Do you want to try again?")
if retry == "no":
break

huangapple
  • 本文由 发表于 2023年7月14日 00:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76681448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定