2013-02-07 205 views
3

我完全新的Python和我的C++这样的代码片段:C++到Python初学者

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

如何改变这部分蟒蛇?到目前为止,我已经尝试过,我没有得到正确的语法或逻辑流程。这是我的:

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'; 
    } 

我无法弄清楚如何将此部分

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

因此改变到Python代码,我是问题有我无法弄清楚如何初始化阵列

int code[12] ; 

这应该如何在Python中,所以我可以执行这段代码!给出:

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

注意,从一种语言到另一种“翻译”的代码并没有真正很好地工作,为的事情,让有很大的意义在另一种语言中可能效率低下且不可读。 –

+0

另外,如果您有两个问题,请将它们分开发布,而不是将其添加到问题中。它会让更多的人回答,并使其作为其他人的资源更有用。 –

回答

5

首先,do..while is not in 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]) 
+0

我应该如何初始化代码数组?或者我们不这样做在python? – thestralFeather7

+0

只需执行'code = []' – Phil

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()str()函数将整数转换为字符串(并将字符串转换为整数)。例如。

>>> a = '' 
>>> len(a) == 12 
True 
>>> b = int(a) 
>>> print b 
12345678912 
>>> str(b) 
'12345678912' 
+0

我该如何初始化一个数组?像int code [12]然后执行第二部分? – thestralFeather7

+1

你可以使用'myList = []'创建一个数组。然后使用'.append()'函数(即'myList.append(3)')将项目添加到列表中。 – Th3Cuber

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变量“码”是一个列表,而不是当然的数组