C ++ for beginners python
I am completely new to python and I have this piece of C ++ code:
do
{
cout << "Make sure the number of digits are exactly 12 : ";
cin >> input ;
} while((input.length()) != 12 );
How do I change this part to python? I've tried this so far, I don't understand what the correct syntax or logical flow would be. This is what I have:
while True:
print("Make sure the number of digits are exactly 12 : ")
input = raw_input()
check = len(input)
if check != 12
break
The above part is solved!
Also, another C ++ snippet: - line
for (int i = 0; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
I cannot figure out how to change this part to python code
code[i] = input.at(i) - '0';
So, the problem I am facing is I cannot figure out how to initialize the array
int code[12] ;
How it should be in python so that I can execute this piece of code! as noted:
int code[12] ;
for (int i = 0; i < 12 ; i++)
{
code[i] = input.at(i) - '0';
}
source to share
First of all, do..while is not in Python
For your first question:
while True:
print "Make sure the number of digits are exactly 12 : "
x = input()
if len(str(x)) == 12:
break
Python is space sensitive, and methods are controlled with tabs and spaces instead of parentheses. Also, you were missing the colon.
For your second question, the code looks like you are taking a character and converting it to a digit. You can just do the type:
for i in range(12):
code[i] = int(x[i])
source to share
For the first piece of code, you can change:
print("Make sure the number of digits are exactly 12: ")
input = raw_input()
To:
input = raw_input("Make sure the number of digits are exactly 12: ")
You don't need a variable either check
, but just do:
if len(input) == 12:
break
Note that after the IF statement, I include :
(the equality test should also be ==
, not !=
). Then all subsequent indentation after the decision is made if the condition True
.
For the second piece of code, you can convert from integer to string (and string to integer) using the int()
and functions str()
. For example.
>>> a = '012345678912'
>>> len(a) == 12
True
>>> b = int(a)
>>> print b
12345678912
>>> str(b)
'12345678912'
source to share
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';
}
translates into
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'))
There are simpler ways to parse a string of digits into their composite values in python, like
code.append(int(input[ind]))
the translation I have provided is agnostic for the purpose of code [may include letters, etc.] although
the variable 'code' in python is a list, not an array, of course
source to share