[英]How to check the given number is digit or not?
How can I check if a number is composed by a single digit?如何检查一个数字是否由单个数字组成?
Here is what I have tried so far:到目前为止,这是我尝试过的:
n=5
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if ???
return True
else:
return False
The output in this case should be `True这种情况下的输出应该是 `True
` `
You can simply do你可以简单地做
def isdigit(n):
return n in range(10)
I'm not saying it's the best way to do it, but it's probably what you meant to do:我并不是说这是最好的方法,但这可能是你想要做的:
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if n == i:
return True
else:
return False
digit(5)
Output:输出:
True
Please pay attention that the else
clause is not part of the if
, but part of the for
, which means that it will be executed only if the loop ended without any return
or break
during the iterations.请注意,
else
子句不是if
的一部分,而是for
一部分,这意味着它只会在迭代过程中没有任何return
或break
循环结束时执行。 You can also not use the else
at all, and just return False
after the loop.您也可以完全不使用
else
,在循环后return False
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.