3

我对 python 完全陌生,我有这个 c++ 代码片段:

do
    {
    cout << "Make sure the number of digits are exactly 12 : ";
    cin >> input ;
    } while((input.length()) != 12 );

如何将此部分更改为 python ?到目前为止,我已经尝试过了,我不知道正确的语法或逻辑流程是什么。这就是我所拥有的:

while True:
  print("Make sure the number of digits are exactly 12 : ")
  input = raw_input()
  check = len(input)
  if check != 12
  break

以上部分解决!

此外,另一个 c++ 片段是:输入是字符串

for (int i = 0; i < 12 ; i++)
    {
     code[i] = input.at(i) - '0';
    }

我不知道如何将此部分更改为 python 代码

code[i] = input.at(i) - '0';

所以,我遇到的问题是我不知道如何初始化数组

int code[12] ;

那应该如何在 python 中,以便我可以执行这段代码!如给定的:

   int code[12] ;
    for (int i = 0; i < 12 ; i++)
      {
        code[i] = input.at(i) - '0';
      }
4

3 回答 3

5

首先,do..while 不在 Python 中

对于你的第一个问题:

while True:
  print "Make sure the number of digits are exactly 12 : "
  x = input()

  if len(str(x)) == 12:
    break

Python 对空格很敏感,方法是使用制表符和空格而不是括号来管理的。你也错过了一个冒号。

对于您的第二个问题,代码看起来像是您正在获取字符并将其转换为数字。您可以简单地进行类型转换:

for i in range(12):
  code[i] = int(x[i])
于 2013-02-08T00:03:25.230 回答
3

对于第一个代码片段,您可以更改:

print("Make sure the number of digits are exactly 12: ")
input = raw_input()

至:

input = raw_input("Make sure the number of digits are exactly 12: ")

您也不需要该check变量,只需执行以下操作:

if len(input) == 12:
  break

请注意,在 IF 语句之后我如何包含一个:(相等性测试也必须是==,而不是!=)。然后,如果条件为 ,则执行决定后进一步缩进的任何内容True

int()对于第二个代码片段,您可以使用andstr()函数将整数转换为字符串(并将字符串转换为整数) 。例如

>>> a = '012345678912'
>>> len(a) == 12
True
>>> b = int(a)
>>> print b
12345678912
>>> str(b)
'12345678912'
于 2013-02-08T00:03:09.320 回答
1
do
    {
    cout << "Make sure the number of digits are exactly 12 : ";
    cin >> input ;
    } while((input.length()) != 12 );

int code[12] ;
    for (int i = 0; i < 12 ; i++)
        {
        code[i] = input.at(i) - '0';
        }

翻译成

while True:
    input = raw_input("Make sure the number of digits are exactly 12 : ")
    if len(input) == 12:
         break
code = []
for ind in range(0,12):
    code.append(ord(input[ind]) - ord('0'))

在 python 中有更简单的方法可以将一串数字解析为它们的组成值,例如

code.append(int(input[ind]))

我提供的翻译与代码的目的无关[可能包括字母等]

python中的变量'code'当然是一个列表而不是一个数组

于 2015-06-05T13:11:20.897 回答