我是 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';
}
最佳答案
第一个问题:
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])
关于python - C++ 到 Python 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14763430/