首页 > 解决方案 > 如何让 Python 程序再次执行自身?

问题描述

我是 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)

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

我想知道如何让程序在同一个窗口中重新启动。我的意思是:我插入x,y和的值z。然后我按回车,程序显示答案。然后它再次要求输入,因此我将能够继续插入值并接收工作日作为答案。

提前致谢!

标签: pythonpython-3.xinput

解决方案


您正在寻找的是一个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

推荐阅读