提前结束一个程序,而不是循环?

Amy*_*ett 5 python

我正在尝试制作一个简短的程序,它将返回一个数字的阶乘,这很好.我遇到的唯一问题是如果用户输入非整数值,程序将结束.

num = input("input your number to be factorialised here!: ")

try:
    num1 = int(num)
except ValueError:
    print("That's not a number!")



if num1 < 0:
    print("You can't factorialise a negative number")
elif num1 == 0:
    print("the factorial of 0 is 1")
else:
        for i in range(1,num1+1):
            ans = ans * i
        print("the factorial of", num, "is", ans)
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 4

解决方案

有更好的方法可以做到这一点,但考虑到您的代码结构,您可以使用else. 请参阅文档

num = input("input your number to be factorialised here!: ")

try:
    num1 = int(num)
except ValueError:
    print("That's not a number!")
else:
    if num1 < 0:
        print("You can't factorialise a negative number")
    elif num1 == 0:
        print("the factorial of 0 is 1")
    else:
        ans = 1
        for i in range(1,num1+1):
            ans = ans * i
        print("the factorial of", num, "is", ans)
Run Code Online (Sandbox Code Playgroud)

else仅当没有抛出异常时该子句才会执行。

建议

为了不泄露你的家庭作业的答案,这里有一些建议你应该看看以清理你的代码:

  1. 你能更有效地利用范围吗?提示:您可以通过将 设为step负整数来迭代递减的数字。
  2. 你能找到摆脱支票的方法吗num1 == 0