用Python运行整个程序后如何重复程序?

时间:2019-05-01 14:24:08

标签: python while-loop main repeat

我写了一个简短的程序,比较两个整数并在最后提供一个适当的答案。我希望程序在没有在'userint'中写入整数的情况下重复自身。

核心程序:

from random import randint
rn = randint(0,5)
print("The randomly generated integer is:",rn)
userint= input("Enter an integer:")

try:
    if userint == rn:
        print("Numbers are equal!")
    elif userint > rn:
        print(userint)
    else:
        print(rn)
except:
    print("You have not entered an integer!")

if input("Do you want to repeat(y/n)").lower()== "  N":
    break

这是我尝试使用的内容:

while True:
    from random import randint
    rn = randint(0,5)
    print("The randomly generated integer is:",rn)
    userint= input("Enter an integer:")

    try:
        if userint == rn:
            print("Numbers are equal!")
        elif userint > rn:
            print(userint)
        else:
            print(rn)
    except:
        print("You have not entered an integer!")

    if input("Do you want to repeat(y/n)").lower()== "  N":
        break

我还尝试了另一种重复程序的方法:

def main():

    from random import randint
    rn = randint(0,5)
    print("The randomly generated integer is:",rn)
    userint= input("Enter an integer:")

    try:
        if userint == rn:
            print("Numbers are equal!")
        elif userint > rn:
            print(userint)
        else:
            print(rn)
    except:
        print("You have not entered an integer!")

    restart = input("Do you want to start again?").lower()
    if restart == "yes":
        main()
    else:
        exit()
main()

在两种情况下,程序都会要求用户输入值。但是,尽管有该值,它仍会运行程序的重新启动部分,而不会对这些值进行实际比较。

有人可以指导我如何修复程序并允许其比较值,如果用户输入的不是整数打印(“您尚未输入整数!”),请问“是否要重新启动?”,然后再次运行该程序?

2 个答案:

答案 0 :(得分:0)

您可以使用isnumeric来检查输入是否为整数。

def main():

    from random import randint
    rn = randint(0,5)
    print("The randomly generated integer is:",rn)
    userint= input("Enter an integer:")
    if userint.isnumeric():
        userint=int(userint)
    try:
        if userint == rn:
            print("Numbers are equal!")
        elif userint > rn:
            print(userint)
        else:
            print(rn)
    except:
        print("You have not entered an integer!")

    restart = input("Do you want to start again?").lower()
    if restart == "yes":
        main()
    else:
        exit()
main()

答案 1 :(得分:0)

问题出在您的try / except块中。如果其中任何一行失败,try块将不会运行该块中包含的任何代码行。在您的情况下,由于userint变量为字符串,而rn为int,因此一行失败。在您的示例上下文中,只需在try块的顶部添加以下行即可解决此问题:

try:
    userint = int( userint )
    ...
except:
    ...

如果无法将userint转换为字符串,则try块将失败,而您将打印错误消息。