Reputation: 53
So, I'm doing some practice before my school assessment, was wondering how I'd make it so that when I enter an integer with a 0 as the first value, it wouldn't convert it into an integer with no zero at the start. Here's a little extract of my program:
initialNumber = int(input("Enter your 10 digit number: "))
while len(str(initialNumber)) != 10:
print("Next time please enter a 10 digit numerical value excluding decimals...")
time.sleep(1)
initialNumber = int(input("Enter your 10 digit number: "))
calculator()
I'm using Python 3.4, I understand that I could do something along the lines of this:
initialNumber = input("Enter your ten digit number")
I understand that by using this it keeps the "0", but I need to convert the string into an integer for arithmetic purposes. Any help would be greatly appreciated :)
Upvotes: 1
Views: 7805
Reputation: 180391
If you want ten individual ints from the input call list on the input and map to int:
initialNumber = list(map(int,(input("Enter your 10 digit number: "))))
In [1]: initialNumber = list(map(int,(input("Enter your 10 digit number: "))))
Enter your 10 digit number: 0123456789
In [2]: initialNumber
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
while True:
initialNumber = input("Enter your 10 digit number: ")
if len(initialNumber) != 10 or not initialNumber.isdigit():
print("Invalid input")
else:
print(list(map(int,initialNumber)))
break
Normally you would use a try/except to check that the input is numeric but allowing negative numbers would not work so as out character count would be wrong.
Upvotes: 0
Reputation: 335
Although personally I do not see the sense doing this. I would create a string variable to hold the leading zeros before performing math operations.
initialNumber = (raw_input("Enter your 10 digit number: "))
while len(str(initialNumber)) != 10:
print("Next time please enter a 10 digit numerical value excluding decimals...")
time.sleep(1)
initialNumber = (raw_input("Enter your 10 digit number: "))
leadingZeros = (len(initialNumber) - len(str(int(initialNumber)))) * "0"
calculator()
After the arithmetic you can easily concatenate the zeros to the beginning the output.
Upvotes: 3