我一直在搜索Stacked / Nested if else语句,elif似乎无法满足我的需要。 目的是打印所有偶数,平方数和立方数,并突出显示哪些既是平方数又是立方数。 这是我的代码:
import math
rn = 0
for n in range(1,100,1):
if rn is 0:
if n%2 is 0:
print(n, " is an even number")
else:
rn = 1
if math.sqrt(n) is int:
print(n, " is a square number")
if n**(1/3) is int:
print(n, " is a Cube number too")
continue
else:
print(n, "is only a square number")
continue
else:
rn = 1
if rn is 1:
if n**(1/3) is int:
print(n, " is a Cube only number")
else:
rn = 0
continue
在递增n之前,代码未移至下一个if语句。
输出:
2 is an even number
4 is an even number
6 is an even number
还有另一种继续或中断但停留在同一循环中的方法吗? 预先感谢
答案 0 :(得分:0)
import math
rn = 0
d=0.
for n in range(1,100,1):
if rn is 0:
if n%2 is 0:
print(n, " is an even number")
else:
rn = 1
if math.sqrt(d).is_integer():
print(n, " is a square number")
if float(n**(1-3)).is_integer():
print(n, " is a Cube number too")
continue
else:
print(n, "is only a square number")
continue
else:
rn = 1
if rn is 1:
if n**(1-3) is int:
print(n, " is a Cube only number")
else:
rn = 0
continue
使用float.is_integer()
可以解决以前的问题,即is int
返回False
进行任何输入。还要注意,这将给出从1到100的所有数字>> {} is a square number
,因为您正在做math.sqrt(d)
并且d
是0
,因此平方根始终是整数{{1 }}