【问题标题】:How do I make the Python program to execute itself again?如何让 Python 程序再次执行自身?
【发布时间】:2019-06-15 02:38:30
【问题描述】:

我是 Python 新手,我正在尝试编写一个持续运行的程序,请求新的输入。我想创建一个文件,以便它打开命令提示符,要求用户输入一些值。用户插入输入,程序返回答案并重新启动,因此用户将能够插入新输入以获得新答案。它将一直执行到用户关闭命令窗口为止。

我创建了一个代码,可以为我提供公历中任何日期的工作日。我使用 John Conway 的“世界末日算法”来编写程序。当我运行它时它工作正常。我创建了一个输入部分,程序要求输入日、月和年。看我下面的代码:

#The first part of my doomsday algorithm here (this is to large to simple paste here).
#The last part is creating the last function, that will evaluate everything

def semana(d,m,a):

#definition of the function "semana". 
#I'm Brazilian and this is the portuguese word for "week". 
#Then I insert the input strings here:

x=eval(input("Dia:"))
y=eval(input("Mês:"))
z=eval(input("Ano:"))

semana(x,y,z)

我在命令提示符下运行程序并输入变量xyz 的值,然后按回车键,程序显示正确答案,但在答案出现后立即终止.

我想知道如何让程序在同一个窗口中重新启动。我的意思是:我插入xyz 的值。然后我按回车,程序显示答案。然后它再次要求输入,这样我就可以继续插入值并接收工作日作为答案。

提前致谢!

【问题讨论】:

  • 使用while True:

标签: python python-3.x input


【解决方案1】:

您正在寻找的是while 循环。只要条件是True,这种控制结构就允许我们执行一组语句。如果条件变为False,我们就跳出循环。

# -*- encoding: utf-8 -*-

def semana():
    x=input("Dia:")
    y=input("Mes:")
    z=input("Ano:")
    print('{}/{}/{}'.format(x,y,z))

while True:
    semana()

示例输出

Dia:6
Mes:14
Ano:2019
6/14/2019

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多