python重新执行一段代码_如何使Python程序再次执行自身?

1586010002-jmsa.png

I'm new to Python and I'm trying to write a program that keep running asking for new inputs. I want to create a file such that it opens the command prompt asking the user to input some values. The user inserts the inputs, the program returns a answer and it restarts so the user will be able to insert new inputs to get new answers. It will be done until the user closes the command window.

I created a code that give to me the weekday of any date in Gregorian Calendar. I used John Conway's "Doomsday Algorithm" to write the program. It works fine when I run it. I created a input section where the program asks for the Day, Month and Year. Look my following code:

#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)

I run the program on command prompt and I enter the values for the variables x,y and z, I press enter and the program shows the correct answer, but it terminates itself right after the answer appears.

I want to know how to make the program to restart in the same window. What I mean is: I insert the values for x,y and z. Then I press enter and the program shows the answer. Then it asks again for the input so I will be able to keep inserting values and receiving the weekday as answer.

Thanks in advance!

解决方案

What your looking for is a while loop. This control structures allows us to execute a set of statements as long as a condition is True. If the condition becomes False, we break out of the loop.

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

def semana():

x=input("Dia:")

y=input("Mes:")

z=input("Ano:")

print('{}/{}/{}'.format(x,y,z))

while True:

semana()

Example output

Dia:6

Mes:14

Ano:2019

6/14/2019

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值