具有“while”循环的PYTHON基本因子算法

时间:2016-10-26 16:34:24

标签: python algorithm while-loop factorial

第一次写道“你想要rety?(y或n)”我总是得到这个输出“错误!再试一次。”之后它的工作正常,但它第一次出错。

def factorial(n):
    r=1
    if n==0:
        return 
    else:
        for i in range(2,n+1):
            r=r*i
        return r

n=int(input("Give a number : "))
b=factorial(n)
print (n,"!", "= ",b)

a=str(input("Do you want rety ? (y or n) \n"))

while (a != "y" or a != "n" or a!="Y" or a!="N"):
    print("wrong ! try again .")
    a=str(input("Do you want rety ? (y or n) \n")) 
    if a=="y" or a=="n" or a=="Y" or a=="N":
        break

while a=="y" or a=="Y":
    n=int(input("Give a number : "))
    b=factorial(n)
    print (n,"!", "= ",b)
    a=str(input("Do you want rety ? (y or n) \n")) 
if (a=="n" or a=="N"):
    print("thanks for using")

1 个答案:

答案 0 :(得分:1)

在第一次循环中将条件从a != "y" or a != "n" or a!="Y" or a!="N"更改为

while a not in ['y', 'Y', 'n', 'N']

说明:

我们说a = "Y",然后a不等于"n"。因此,or的条件始终为True

如果您对or逻辑感兴趣,请将其写为(但not in list更清晰):

while not (a == "y" or a == "n" or a=="Y" or a=="N")