【问题标题】:While loop not able to handle the value tenWhile 循环无法处理值 10
【发布时间】:2019-11-17 12:39:47
【问题描述】:

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

【问题讨论】:

  • 你的意思是print("Your destiny number is 1")永远不会执行吗?
  • @JonClements 是的。
  • 我输入了“abcd”,得到的结果是 1 而不是 10。
  • 即使你输入了“BP”的名字?
  • 输入“abcd”时提供的代码可以正常工作...

标签: python python-3.x


【解决方案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)

【讨论】:

  • 认为你也稍微有点过于复杂了......你最好避免使用 while(len(...)) 检查并执行destiny = sum(int(c) for c in str(destiny)) 并完成它。跨度>
  • @JonClements 这可能是真的,但我想处理(不太可能的情况)总和也是两位数
  • 这行得通。我的很复杂,因为我刚刚开始并且对您程序中的步骤不太熟悉。非常感谢。
  • @OferSadan 如果是像斯嘉丽约翰逊这样的长名字,总和将是两位数。这是开始的问题。
  • @MuhammadIsmail 我想,这就是为什么你根本不需要检查等于10 的东西。感谢您接受答案,如果您认为它很好,请随时点赞
猜你喜欢
  • 2017-06-15
  • 2014-08-09
  • 2017-05-05
  • 2018-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-07
  • 2017-09-27
相关资源
最近更新 更多