#This will ask the user to enter a 7 digit number
#then it would calculate the modulus 11 check digit
#then would show the user the complete 8 digit number
weight=[8,7,6,5,4,3,2]
number= input("Please enter your 7 digit number: ")
#If the user enters more than 7 characters it will prompt the user to try again
while len(number) > 7:
number=input ("Error! Only 7 numbers allowed! Try again: ")
#This puts the 7 digit number into a list
account_number=number
#This converts the string in the list into a integer
account_number = [int(i) for i in account_number]
#This separates the numbers into multple values every character
list(account_number)
#This multiplies the account number by the weight
num1=weight[0]*account_number[0]
num2=weight[1]*account_number[1]
num3=weight[2]*account_number[2]
num4=weight[3]*account_number[3]
num5=weight[4]*account_number[4]
num6=weight[5]*account_number[5]
num7=weight[6]*account_number[6]
#This adds up the all the answers above
num8=num7+num6+num5+num4+num3+num2+num1
#The use of % divides the number and gives the remainder
remainder=num8%11
#This generates the final check digit
check_number=11-remainder
#This adds the check number to the 7 digit number (account number)
account_number.insert(7,"{0}".format(check_number))
#This gives the user the total 8 digit number
print ("Your account number is {0}".format(account_number))
Run Code Online (Sandbox Code Playgroud)
最后,帐号显示如下[1,2,3,4,5,6,7].如何在1234567没有逗号和方括号的情况下显示它?
>>> "".join(map(str,account_number))
Run Code Online (Sandbox Code Playgroud)
这首先将int转换为str,然后将它们连接在一起,没有空格
例:
>>> a = [1,2,3]
>>> map(str,a)
['1', '2', '3']
>>> "".join(map(str,a))
'123'
>>>
Run Code Online (Sandbox Code Playgroud)
在您的情况下,更改为:
account_number = "".join(map(str, account_number))
print ("Your account number is {0}".format(account_number))
Run Code Online (Sandbox Code Playgroud)
跟进评论:
while len(number) != 7:
number=input ("Error! Only 7 numbers allowed! Try again: ")
Run Code Online (Sandbox Code Playgroud)