Denis - 1 month ago 5
Python Question

# basic FACTORIAL algorithm on PYTHON with "while" loop

For the first time wrote "Do you want rety ? (y or n)" I always get an this output "wrong ! try again .". After that its working good but it first time gives error.

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

Change your condition in first while loop from `a != "y" or a != "n" or a!="Y" or a!="N"` to

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

Explanation:

Let say `a = "Y"`, then `a` won't be equal to `"n"`. Hence your condition with `or` will always be `True`.

If you are interested in `or` logic, write it as (but `not in list` is cleaner):

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