问题描述:
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false.
eg:
validate_pin("1234") == True
validate_pin("12345") == False
validate_pin("a234") == False
代码实现:
#codewars第一题(7)
def validate_pin(pin):
#return true or falsen
numbers = ['0','1','2','3','4','5','6','7','8','9']
_lenth = len(pin)
i = 0
if _lenth == 4 or _lenth == 6: #or 是 或 ; and 是 且 | 和 & 是位运算符
while i < _lenth:
if pin[i] in numbers:
i += 1 #python不支持 i++这样自加 要用 i = i + 1 或者 i += 1
else: return False
return True #True 和 False 开头字母都要大写
else:
return False
validate_pin("123a")
#类型匹配测试
numbers = [1,2,3] #list中存的类型是什么 就一直是什么 这里面是int类型 但是numbers是list类型
s = "123a" #字符串存储后一定是字符串类型 无论存储什么在里面都转化为字符串了 要使用的话可以用强制转化
int(s[0]) in numbers