简体   繁体   English

Python程序不起作用-非常简单

[英]Python program won't work - very simple

Basically for this assignment I need to convert a name into a 'secret number' by summing the value I assigned each letter. 基本上,对于此分配,我需要通过将我分配给每个字母的值相加来将名称转换为“秘密号码”。 Everything works so far but when I try to sum it up it gives me an error. 到目前为止,一切正常,但是当我尝试总结时,这给了我一个错误。 I think I need to convert the letters into their number form but everything i've tried so far won't work. 我想我需要将字母转换为数字形式,但到目前为止,我尝试过的所有方法均无效。

eg 例如

total_name =0 for c in end_name
    c_int = int(c)          
    total_name+= c_int

Any help would be greatly appreciated! 任何帮助将不胜感激! Here's my code: 这是我的代码:

'a' ==1
'b'==2
'c'==3
'd'==4
'e'==5
'f'==6
'g'==7
'h'==8
'i'==9
'j'==10
'k'==11
'l'==12
'm'==13
'n'==14
'o'==15
'p'==16
'q'==17
'r'==18
's'==19
't'==10
'u'==21
'v'==22
'w'==23
'x'==24
'y'==25
'z'==26

#input:ask user to enter their name
#processing: convert name into all lower case then calculate number
#output: return name and reduction to user

name = input('Name:')
new_name= str.lower(name)
end_name=new_name.replace(" ","")

print('Your "cleaned up" name is:',end_name)

total_name =0
for c in end_name

    total_name+= c

print('Reduction:',total_name)

您缺少冒号:

for c in end_name:

You will need the ord() function to convert a character into a number. 您将需要ord()函数将字符转换为数字。

The ASCII code for 'A' is 65, so you could subtract 64 to scale to your preferred offset. “ A”的ASCII码为65,因此您可以减去64以缩放到首选偏移量。

total_name=0
for c in end_name:
    total_name+=ord(c)-64

For lowercase, 'a' is ASCII code 97, but then you'd get negative numbers for any uppercase. 对于小写字母,“ a”是ASCII码97,但是对于任何大写字母,您都会得到负数。 You could just as well normalize the entire string to uppercase (or lowercase, your choice) before the loop. 您也可以在循环之前将整个字符串规范化为大写(或选择小写)。

Here is one approach: 这是一种方法:

values = dict(zip("abcdefghijklmnopqrstuvwxyz", range(1,27)))
name = raw_input('Name:')
score = 0

for l in name.lower():
    score += values[l]

For the input Jason I get the value 59 对于输入Jason我得到值59

_d = {chr(k): k for k in range(97, 123)}

inp = raw_input().replace(" ", "").lower()

print ''.join([str(_d[ele]) for ele in inp])

Or use sum if you want as sum 或使用总和(如果要作为总和)

print sum([str(_d[ele]) for ele in inp])

Output: 输出:

as d f g
97115100102103

This problem can be done in two lines: 此问题可以通过两行来完成:

name = input('Name: ').lower().replace(" ", "")
print(sum(ord(letter) - ord('a') + 1 for letter in name))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM