需要帮助添加一个循环来重启Python中的程序

时间:2015-11-24 20:10:36

标签: python loops restart

到目前为止,这就是我所拥有的。

import random

answer1=("Absolutely!")
answer2=("No way Pedro!")
answer3=("Go for it tiger.")
answer4=("There's different ways to do this.")
answer5=("Definitely not")

print("Welcome to the Magic 8 Ball game-use it to answer your questions...")

questio = input("Ask me for any advice and I'll help you out. Type in your question and then press Enter for an answer")

print("Shaking... \n" * 4) 

choice=random.randint(1,5)

if choice == 1:
    answer=answer1
elif choice == 2:
    answer=answer2
elif choice == 3:
      answer=answer3
elif choice == 4:
      answer=answer4

elif choice == 5:
      answer=answer5


print(answer)

restart = input("Would you like to try again?")

if restart == "yes" or "y":

现在我需要为此添加一个循环,所以在完成后显示"你想再试一次吗?"。输入yes后,程序将从顶部重新开始。

3 个答案:

答案 0 :(得分:1)

尝试在代码中添加这样的循环:

restart = ''

while restart.upper() not in ['NO', 'N', 'EXIT']:
    # ...  
    # Your code here
    # ...

    restart = input("Would you like to try again?")

这实际上是将restart重新初始化为空字符串。然后循环仅在restart != 'NO'时开始。在循环结束时,我们会为restart的用户获取新值,这样如果他们说'no''n',则循环不会重新开始。

还有很多其他方法可以执行此操作,例如您可以检查用户是否输入肯定答案('yes''y')或放置{{1}如果他们说break

希望这能让你开始。

答案 1 :(得分:0)

在导入行添加while True:后将整个代码缩进到while循环。然后在最后这样:

    restart = input("Would you like to try again?")

    if restart == "yes":
        continue
    else:
        break

进一步解释。继续将跳回到顶部pass也可以。 break将退出循环。祝你好运!

答案 2 :(得分:0)

最简单的方法是使用while循环:

import random

while True:
    answer1=("Absolutely!")
    answer2=("No way Pedro!")
    answer3=("Go for it tiger.")
    answer4=("There's different ways to do this.")
    answer5=("Definitely not")

    print("Welcome to the Magic 8 Ball game-use it to answer your questions...")

    questio = input("Ask me for any advice and I'll help you out. Type in your question and then press Enter for an answer ")

    print("Shaking... \n" * 4) 

    choice=random.randint(1,5)

    if choice == 1:
        answer=answer1
    elif choice == 2:
        answer=answer2
    elif choice == 3:
          answer=answer3
    elif choice == 4:
          answer=answer4

    elif choice == 5:
          answer=answer5

    print(answer)

    restart = input("Would you like to try again? ")

    if restart == "yes" or "y":
        continue

    else:
        break