I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if a<0:
print "Please enter a number greater than or equal to 0"
else:
if(a==1 or a==0 ):
print "1"
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)
the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.
Comparing string with number returns False
as result
'-2'< 0 ---> False --> if condition will be skipped
Convert the string to integer since factorial are only applied to integer
int('-2') < 0 ---> True --> if condition will be executed
x = raw_input().split(" ")
returns strings data type in a list
so you can't use int
for the entire list x
,
only one string at the time
When invoking the if condition you are considering only one element in the list,
then convert from string to int before comparing to 0 --> int(a) < 0
The second point is related to indentation
print (",".join(c))
should be included inside theelse
loop
Also
if(a==1 or a==0 ):
print "1"
is not needed as it has been taken care in the for loop below
x=raw_input().split(" ")
c=[]
for a in x:
b=1
if int(a) < 0:
print "Please enter a number greater than or equal to 0"
else:
for i in range(1,int(a)+1):
b=b*i
c.append(str(b))
print ",".join(c)