我在 for 循环中使用 If 语句,但即使满足条件,If 语句也会被跳过
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)
该程序是找到阶乘,我得到了结果。如果有人输入负数,则不应返回阶乘,但会返回。我只想知道为什么会跳过 if 和 else 条件。
比较字符串与数字返回False
结果
'-2'< 0 ---> False --> if condition will be skipped
将字符串转换为整数,因为阶乘仅适用于整数
int('-2') < 0 ---> True --> if condition will be executed
x = raw_input().split(" ")
在列表中返回字符串数据类型
所以你不能int
用于整个列表x
,
当时只有一根弦
调用 if 条件时,您只考虑列表中的一个元素,
then convert from string to int before comparing to 0 --> int(a) < 0
第二点与缩进 有关,
print (",".join(c))
应包含在else
循环内
还
if(a==1 or a==0 ):
print "1"
不需要,因为它已在下面的 for 循环中得到照顾
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句