1

大家!

我是 Python 新手,正在使用第 3 版。我已经在 PHP 中进行了编程,并且我已经完成了一个脚本,在该脚本中我输入了一个字符串(名称如 'John'),脚本返回与此名称关联的数字,基于来自 ASCII 表的计算。

公式为 => (ASCii 代码 - 65)%9+1。

这是我在 PHP 中的脚本:

<?php

$entry=strtoupper("Jack");
$value = 0;
for ($i = 0; $i < strlen($entry); $i++) {
if ($entry[$i] >= "A" && $entry[$i] <= "Z") {
    $temp = (ord($entry[$i]) - 65)%9 + 1;
    $value += $temp;
}
}
$result = $value%9;
if ($result == 0) $result = 9;
echo $result;
?>

上面的结果应该是 7。

这是我在 Python 中的脚本:

entry = input("Type your name: ")
name = entry.upper()
value = 0

for letter in range(len(name)):
    while letter:
        temp = int(ord(name[letter])-65)%9+1
        value += temp
result = value%9
if result == 0:
    result = 9
print(result)

好吧,它不起作用,因为 Python 似乎不像我在 PHP 中使用的第一个 IF 语句那样遍历字母。有谁知道我该如何解决这个问题?

提前致谢!!!上帝保佑你们!

4

1 回答 1

0

There are a few problems with your python code.
The biggest one is the if from php somehow becoming a while(and an infinite one) in python.

The direct translation to python would be(and it should make the code work):

if 'A' <= name[letter] <= 'Z':


But, you should never loop through indices in python.
Instead, loop directly over the values you want to work with.

Instead of:

for i in range(len(some_list)):
    # do stuff with some_list[i]

You should do:

for item in some_list:
    # do stuf with item


Edit:

This is how the loop would look written in a more pythonic way:

for letter in name:
    if 'A' <= letter <= 'Z':
        value += (ord(letter) - 65) % 9 + 1

Also, you can see here that the int() call and the temp variable are not really needed.

于 2012-12-13T20:41:09.693 回答