如何让python程序重新运行自己

时间:2016-11-13 09:57:25

标签: python

我希望下面的代码能够自动重新运行任何想法吗?顺便说一句我是堆栈溢出和python本身的新手,所以如果我做错什么请告诉我,谢谢

import sys
import os
import random 
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)


def question_asker_and_answerer():
    q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
    if q2 == random_num_1 + random_num_2:
        the_questions = True
        if the_questions == True:
            return (answer_correct_message)
        else:
            return (answer_wrong_message)
    else:
        the_questions = False
        if the_questions == True:
            return (answer_correct_message)
        else:
            print(answer_wrong_message)


print question_asker_and_answerer()

2 个答案:

答案 0 :(得分:2)

这不是您需要重新运行程序的情况。这种要求是您希望脚本作为守护程序运行的时候。这只是创建循环的问题

ChDir "S:\Credit_Risk\MIS\Consolidated Customer profile Macro\Securities"

Workbooks.Open Filename:= _
    "S:\Credit_Risk\MIS\Consolidated Customer profile Macro\Securities\Enterprise  pending cases as at end of Oct.2016.xls"

答案 1 :(得分:1)

这里有两个问题:

  • 如何迭代;
  • 如何确保各个随机选择的变量在每次传递时都不同。

只是循环现有函数,或者让它递归(如在其他几个答案中)解决了第一个问题(实际上,递归确实没有,因为Python没有尾巴-call消除,所以它最终将耗尽堆栈。)

要解决这两个问题,您需要将随机选择的变量置于函数的本地,然后循环。我也修改了它,所以它返回字符串打印而不是打印它,如果答案错误(函数的最后一行)。

import sys
import os
import random 

def question_asker_and_answerer():
    answer_correct_message = random.choice(['Well done', 'Correct answer',
                                            'Nice one','Thats correct!'])
    answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
    random_num_1 = random.randint(1,10)
    random_num_2 = random.randint(1,10)
    q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
    if q2 == random_num_1 + random_num_2:
        the_questions = True
        if the_questions == True:
            return (answer_correct_message)
        else:
            return (answer_wrong_message)
    else:
        the_questions = False
        if the_questions == True:
            return (answer_correct_message)
        else:
            return (answer_wrong_message)


while True:
    print question_asker_and_answerer()