Python从头开始重新运行一个程序

时间:2015-02-22 12:49:54

标签: python performance

我想问,
有没有办法让你可以在Python 3.x或2.x上重新运行任何类型的程序,而不需要while循环?

例如,我可以使用任何代码块来执行此操作:

if user says yes:
    re - run code from top
else:
    end program

例如,举个例子:

output Hello what would you like to do?
     if user says internet
           response = go to internet.
     if response = true
           go to start.
     else
           end program

def internet
     open web page.
     output Would you like to do anything else?
     if input is yes
          return True
     else
          return False

谢谢, 朱迪。

注意,上面的代码是模型。

4 个答案:

答案 0 :(得分:3)

这有效......

>>> from itertools import count
>>> c = count()
>>> for i in c:
...   i = input("what is your input? ")
...   if str(i) == "internet":
...     print "internet"
...   elif i == True:
...     continue
...   else:
...     break
... 
what is your input? True
what is your input? "internet"
internet
what is your input? "foo"
>>> 

但它作为while循环仍然好得多。

答案 1 :(得分:1)

while实际上是这里最好,最干净的解决方案。请记住将所有可重复使用的功能放在函数或类中。 E.g:

def main():
    while True:
        fun()
        ask user
        if user says no:
            break

def fun():
    # your functionality goes here

if __name__ == "__main__":
    main()

答案 2 :(得分:0)

while user says no:
    if user says yes:
        do stuff
        break

这摆脱了其中一个陈述。

答案 3 :(得分:-1)

您可以使用os.exec*()

重新开始执行脚本

希望这有帮助!