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
`
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. You can also not use the else
at all, and just return False
after the loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.