【问题标题】:how to fix error in factorial print program?如何修复阶乘打印程序中的错误?
【发布时间】:2020-12-13 02:23:27
【问题描述】:

我尝试制作这个简单的程序来查找输入数字的阶乘。 但是我无法弄清楚的地方有一个错误: 当我使用 raw_input() 函数时,它会显示 'none' 输出,如果我使用 input() 函数名,则会显示错误。帮我找bug。

program_active=True
while program_active:
    def fact(n):
        if n==0:
            return 1
        elif not isinstance(n, int):
            while not isinstance(n, int):
                print "Factorial is defined only for Positive integers"
                try:
                    n=int(raw_input())
                except ValueError as ve:
                    pass
        elif n<0:
            print "Factorial is defined only for Positive integers"
        else:
            step1=fact(n-1)
            step2=n*step1
            return step2
    print"input a number to check its factorial"
    n=raw_input()
    print fact(n)
    print
    print
    print
    print "do yo want to run the program again? (y/n)"
    run=raw_input()
    while run[0].upper()!='Y' and run[0].upper()!='N':
        print"****invalid input****"
        run=raw_input('say y/n \n')
    if run[0].upper()=='N':
        program_active=False
        print "goodbye"

使用raw_input() 函数时出现错误


> input a number to check its factorial 
> 8 
> Factorial is defined only for Positive integers 
> 8 
> None
> 
> 
> 
> do yo want to run the program again? (y/n) n goodbye

【问题讨论】:

标签: python function runtime-error factorial nonetype


【解决方案1】:

您的代码不起作用

您首先输入的8string,所以它会经历以下条件:

elif not isinstance(n, int):
     while not isinstance(n, int):
          print "Factorial is defined only for Positive integers"
          try:
              n=int(raw_input())
          except ValueError as ve:
              pass

之后,当你输入新的8,然后将其转换为int,它会打破while循环并退出fact()函数,而不用在下面显示的else条件下计算阶乘部分。

else:
     step1=fact(n-1)
     step2=n*step1
     return step2

为了FIX这个问题,我建议你将输入验证部分从def fact()移出。

代码:

program_active=True
while program_active:
    def fact(n):
        if n==1:
            return n
        elif n==0:
            return 1
        else:
            step1=fact(n-1)
            step2=n*step1
            return step2
    while True:
      print"input a number to check its factorial"
      try:
        n=int(raw_input())
      except:
        print("Factorial is defined only for integer")
        continue
      if n < 1:
        print 'Factorial is defined only for Positive integer'
        continue 

      x = fact(n)
      print x

输出:

> input a number to check its factorial 
> 8  
> 40320

这段代码应该可以工作。

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    相关资源
    最近更新 更多