输入特定的代码后,我可以重播代码吗?

时间:2019-06-26 23:08:22

标签: python recursion

我对编程非常陌生,如果这是一个简单的问题,我感到抱歉。我希望代码在特定用户输入后能够重播,而不必每次都手动运行代码。

我在这里浏览了类似的问题,发现其他人也有类似的问题,但我不明白给出的答案。我在一开始就尝试过set "filenames=" for /F "delims=" %%F in (' forfiles /D -5 /C "cmd /C echo/@file" ') do ( call set "filenames=%%filenames%% %%F" ) ,并将def main()放在要重设代码的位置,但是随后就没有出现输入用户的提示。

main()

2 个答案:

答案 0 :(得分:4)

您已经关闭。您需要在python文件中调用main才能在脚本首次运行时实际执行它

def main():
    number=int(input("Please enter an integer between 0 and 127: "))
    if number>127 or number<0 :
        print("I'm sorry, that is not an acceptable value. Please try again")
        main()
    elif number<=127 and number>=0 :
        print("WIP")
    else:
        print("I'm sorry, something went wrong. Please try again and be sure to enter an integer between 0 and 127.")
        main()

main()

答案 1 :(得分:-2)

欢迎使用编码!这是尝试解决问题的巧妙尝试。为了使其正常工作,您需要确保在代码底部调用主函数(除非您告知函数,否则函数将无法运行!

def main():
    number=int(input("Please enter an integer between 0 and 127: "))
    if number>127 or number<0 :
        print("I'm sorry, that is not an acceptable value. Please try again")
        main()
    elif number<=127 and number>=0 :
        print("WIP")
    else:
        print("I'm sorry, something went wrong. Please try again and be sure to enter an integer between 0 and 127.")
        main()

main()

虽然这将起作用,但可能会导致问题。我建议为此使用while循环:

while True:
    number=int(input("Please enter an integer between 0 and 127: "))
    if number>127 or number<0 :
        print("I'm sorry, that is not an acceptable value. Please try again")
    elif number<=127 and number>=0 :
        print("WIP")
        break;
    else:
        print("I'm sorry, something went wrong. Please try again and be sure to enter an integer between 0 and 127.")

while循环将在您指定的条件为true的情况下运行。您可以使用break关键字,早点break跳出循环。