PYTHON 上带有 "while" 循环的基本 FACTORIAL 算法

basic FACTORIAL algorithm on PYTHON with "while" loop

第一次写 "Do you want rety ? (y or n)" 我总是得到这样的输出 "wrong ! try again ."。之后它工作正常但第一次出错。

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")

将第一个 while 循环中的条件从 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")