如何在不让用户关闭shell的情况下重复程序?

时间:2015-11-15 05:19:02

标签: python shell random numbers generator

我无法找到让用户重复代码而不必退出shell的方法。这是我到目前为止所做的。

https://....

我想知道如何将所有这些代码应用于一个变量或重复,而不必编写50次。

3 个答案:

答案 0 :(得分:2)

我建议将整个事情包含在while循环中。

start = True
while start == True:
    """your code here"""
    answerAgain = raw_input("Do you want to restart this program ? ")
        if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
            start = True
        else:
            start = False

如果start == True,那么整个代码将再次运行。

我还建议您使用列表作为回复。

responses = ["Super Close", "Pretty Close", "Fairly Close", "Not Really Close", "Far"]

通过这种方式,您可以使用差异映射到相应的响应:

print responses[abs(answer - randomNum) - 1]

答案 1 :(得分:0)

将代码置于while循环中以重复它。

start = True

while start:

    # code

    if answerAgain.lower() in ('no', 'niet', 'bye'):
        start = False

答案 2 :(得分:0)

  1. 如果您使用用户提供的数字和随机数之间的绝对值,您只需记录一半的案例(即-1和+1得到相同的处理)。
  2. 不是在每个案例之后要求他们的新答案,而是将此代码移到主循环的顶部,因为它在程序开始时请求并且跟随所有错误的'答案。
  3. 对于使用情况,您可能希望转换所有字词'答案为小写,因为案件似乎并不重要。
  4. 您可以使用quit()彻底退出程序。
  5. 所以也许这样:

    import random
    
    while(True):
        randomNum = random.randint(1, 10)
        answer = 0
        while abs(answer - randomNum) > 0:
            answer = int(input("Try to guess a random number between 1 and 10. "))
            if abs(answer - randomNum) == 1:
                print("Super Close")
            elif abs(answer - randomNum) == 2:
                print("Pretty Close")
            # the other cases ...
    
        # gets here if abs(answer - randonNum) == 0, i.e. they guessed right
        print("Good Job!", randomNum)
        answerAgain = input("Do you want to restart this program ? ")
        if answerAgain.lower() in ["yes", "ya", "y", "okay", "sure", "si", "start"]:
            pass
        else:
            print("See ya next time!")
            quit()