需要帮助添加循环以重新启动Python中的程序 [英] Need help adding a loop to restart program in Python
问题描述
到目前为止,这就是我所拥有的.
So far this is what I have got.
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":
现在我需要为此添加一个循环,以便在完成后显示您是否想再试一次?".输入是"后,程序将从顶部重新开始.
now I need to add a loop to this so after its done it displays "Would you like to try again?". After entering yes the program starts again from the top.
推荐答案
尝试将这样的循环添加到您的代码中:
Try adding a loop like this to your code:
restart = ''
while restart.upper() not in ['NO', 'N', 'EXIT']:
# ...
# Your code here
# ...
restart = input("Would you like to try again?")
这实际上是将重启初始化为空字符串.然后,循环仅在restart != 'NO'
时开始.在循环结束时,我们从用户那里获得了restart
的新值,因此,如果他们说'no'
或'n'
,则循环不会再次开始.
This is essentially initializing restart as an empty string. Then the loop is only going to start while restart != 'NO'
. At the end of the loop we're getting a new value from the user for restart
so that if they say 'no'
or 'n'
the loop won't start again.
还有许多其他方法可以执行此操作,例如,可以检查用户是否输入了肯定答案('yes'
或'y'
),或者如果他们说
There are lots of other ways to do this, such as the inverse where you could check to see if the user entered a positive answer ('yes'
or 'y'
) or putting a break
if they say 'no'
.
希望这可以帮助您入门.
Hopefully this gets you started.
这篇关于需要帮助添加循环以重新启动Python中的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!