python - 如何让 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)
我在命令提示符下运行程序并输入变量的值x
,y
然后z
按 Enter 键,程序显示正确的答案,但它在答案出现后立即终止。
我想知道如何让程序在同一个窗口中重新启动。我的意思是:我插入x
,y
和的值z
。然后我按回车,程序显示答案。然后它再次要求输入,因此我将能够继续插入值并接收工作日作为答案。
提前致谢!
解决方案
您正在寻找的是一个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
推荐阅读
- android - Google Play 应用链接链接到 Play 主页而不是应用详细信息页面
- datetime - SSRS 无效输入参数
- mysql - 检查字符串编号
- python-3.x - AWS Step Function 中的 lambda 能否知道其当前 AWS Step Function 的执行 ID?
- c - Visual Studio 2017 是否对 C 进行语法检查?
- prometheus - Prometheus 1.8/2.2.1 scrape 给出“无令牌”错误 - promtool 仅显示几个警告
- angular - angular-l10n 与 ngx-translate 的优缺点
- hadoop - 如何删除 Hive 中的两个分区列之一?
- javascript - 选中或取消选中复选框中的问题
- angular - 动态更改提供者