该程序应给出名称的目的地号码。对于所有其他用户输入,它给出正确的结果。但是,如果用户名的目的地号码为10,则输出为10而不是1。while循环应该这样做。我试图通过添加打印语句来规避它,但是它仍然不起作用。哪里出了问题?
#!usr/bin/env python3
name = input("Please Enter Your Full Name Without Spaces in between: ")
if name.isalpha():
name1 = name.upper()
initsum = 0
d = {'A':1,
'B':2,
'C':3,
'D':4,
'E':5,
'F':8,
'G':3,
'H':5,
'I':1,
'J':1,
'K':2,
'L':3,
'M':4,
'N':5,
'O':7,
'P':8,
'Q':1,
'R':2,
'S':3,
'T':4,
'U':6,
'V':6,
'W':6,
'X':5,
'Y':1,
'Z':7}
name2 = list(name1)
initsum = 0
for chr in name2:
initsum += d[chr]
if initsum == 10:
print("Your destiny number is 1")
else:
check = str(initsum)
if len(check)>1:
tot=0
while(initsum>0):
dig=initsum%10
tot=tot+dig
initsum=initsum//10
print("Your destiny number is", tot)
else:
print("Your destiny number is", initsum)
else:
print("Name is invalid")
答案 0 :(得分:1)
您已经过多地使此功能复杂化了。同一件事的一个简单示例是:
name = input("Please Enter Your Full Name Without Spaces in between: ")
destiny = sum(d[char] for char in name.upper())
while len(str(destiny)) > 1:
destiny = sum(int(x) for x in str(destiny))
如果您不熟悉sum
(或者您想要更长的可读性版本),则基本上与执行此操作相同:
name = input("Please Enter Your Full Name Without Spaces in between: ")
destiny = 0
for char in name.upper():
destiny += d[char]
while len(str(destiny)) > 1:
tmp = destiny
destiny = 0
for char in str(tmp):
destiny += int(char)