While循环无法处理值10

2024-04-20 07:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序应该给出一个名字的命运号。它为所有其他用户输入提供正确的结果。但是,如果用户名的命运号为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")

Tags: nameinnumberyourifiselseprint
1条回答
网友
1楼 · 发布于 2024-04-20 07:38:17

你把这个函数复杂化了太多。一个简单的例子是:

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)

相关问题 更多 >