Python3计算while循环输出的总和

时间:2016-11-23 05:03:38

标签: python-3.x while-loop

我刚开始使用python3并尝试了将数字分配给字母表并计算总数的想法。

例如:如果输入是"嗨"我的输出应该来了#6; 6" (H是5,我是1所以总数是6)

我不知道如何将while循环输出的输出相加。

name = input("Enter Your name ")

name =name.upper()

name = list(name)

print(name)

items = {'A':'1', 'I':'1', 'J':'1', 'Q':'1','Y':'1',
     'B':'2', 'K':'2', 'R':'2',
     'C':'3', 'G':'3', 'L':'3', 'S':'3',
     'D':'4', 'M':'4', 'T':'4',
     'E':'5', 'H':'5', 'N':'5', 'X':'5',
     'U':'6', 'V':'6', 'W':'6', 'O':'7', 'Z':'7', 'F':'8', 'P':'8', '.':'0'}

counter = 0

x = len(name)-1


while counter <=x:

    names = name[counter]

    if names in items:

       new_name = (items[names])      

    else:

       print('no')


name_int = int(new_name)

print(name_int)

counter = counter +1

1 个答案:

答案 0 :(得分:0)

这应该适合你:

name = input("Enter Your name ")

name =name.upper()

name = list(name)

print(name)

items = {'A':'1', 'I':'1', 'J':'1', 'Q':'1','Y':'1',
     'B':'2', 'K':'2', 'R':'2',
     'C':'3', 'G':'3', 'L':'3', 'S':'3',
     'D':'4', 'M':'4', 'T':'4',
     'E':'5', 'H':'5', 'N':'5', 'X':'5',
     'U':'6', 'V':'6', 'W':'6', 'O':'7', 'Z':'7', 'F':'8', 'P':'8', '.':'0'}

counter = 0

x = len(name)-1

total = 0

while counter <=x:

    names = name[counter]

    if names in items:

       new_name = (items[names])      
       total += int(new_name)

    else:

       print('no')
    counter += 1


print(total)

但是,您可以用更多pythonic 方式编写代码:

name = input("Enter Your name ")
items = {'A':1, 'I':1, 'J':1, 'Q':1,'Y':1,
     'B':2, 'K':2, 'R':2,
     'C':3, 'G':3, 'L':3, 'S':3,
     'D':4, 'M':4, 'T':4,
     'E':5, 'H':5, 'N':5, 'X':5,
     'U':6, 'V':6, 'W':6, 'O':7, 'Z':7, 'F':8, 'P':8, '.':0}
total = 0
for ch in name.upper():
    total += items(ch) if ch in items else 0
print total