3 回答
TA贡献1820条经验 获得超10个赞
您可以添加break和for..else。break将结束循环。
my_l1:str = "0101011"
for character in my_l1:
if character != '0' and character != '1':
print (f"{my_l1} is not a binary number")
break
else:
print (f"{my_l1} is a binary number")
印刷:
0101011 is a binary number.
您可以使用以下方法重写代码all():
my_l1:str = "0101011"
if all(ch=='0' or ch=='1' for ch in my_l1):
print (f"{my_l1} is a binary number")
else:
print (f"{my_l1} is not a binary number")
TA贡献1830条经验 获得超9个赞
my_l1:str = "0101011"
isBinary=True ## We Assume it's True (i.e, the number is a binary) until we prove to
## the contrary, so this boolean variable is used to check (if binary
## or not)
for character in my_l1:
if character != '0' and character != '1':
sBinary=False ## once we find a number in the list my_l1 different
## than "0" and "1" it is not necessary to continue
## looping through the list, because the number is not
## a binary anymore, so we break in order to consume
## time
break
if isBinary: ## i.e, if isBinary==True then do :
print (f"{my_l1} is a binary number")
else:
print(f"{my_l1} is not a binary number")
TA贡献2012条经验 获得超12个赞
尝试这个:
def isBinary(num: str):
for i in num:
if i not in ["0","1"]:
return False
return True
if isBinary("000101") == True:
print("000101 is binary")
添加回答
举报