我有这个小信用卡验证程序,用户必须输入一个8位整数。该程序运行正常,我唯一的问题似乎是将用户输入限制为8位数。
prompt = "Please, enter the 8 digit number of your card: "
while True:
try:
userinput = int(raw_input(prompt))
except ValueError:
print('The gematric value must be an 8 digit integer. Try again')
else:
break
userinput = str(userinput)
a = int(userinput[7])+int(userinput[5])+int(userinput[3])+int(userinput[1])
b1 = str(int(userinput[6])*20)
b2 = str(int(userinput[4])*20)
b3 = str(int(userinput[2])*20)
b4 = str(int(userinput[0])*20)
y = int(b1[0])+int(b1[1])+int(b2[0])+int(b2[1])+int(b3[0])+int(b3[1])+int(b4[0])+int(b4[1])
x = (a+y)
if x % 10 == 0:
print('The card number you entered is valid!')
else:
print('The card number you entered is invalid!')
我知道len()不适用于整数。那么我如何将这个8位数限制纳入我的真正循环中呢?
任何帮助都将不胜感激。
答案 0 :(得分:3)
请尝试以下操作。
try:
userinput = raw_input(prompt)
if len(userinput ) > 8:
raise ValueError()
userinput = int(userinput)
except ValueError:
...