Reputation: 83
I am writing a program on python that will allow the user to input any three digit number and will output the number as separate digits.
This is what I have right now
val = int(raw_input ("Type your three digit number please:"))
print 'The first digit is {}' .format (val // 100)
print 'The second digit is {}'.format (val % 100)
print 'The third digit is {}'.format (val % 10)`
However, for the the second digit I am not sure how to retrieve that. I know the number should not be 100 as it returns the last two digits to me then.
Can someone please help me?
Also does anyone know how I would then proceed to adding the digits up?
Upvotes: 0
Views: 5231
Reputation: 27875
How about this one?
val = raw_input("Type your three digit number please: ")
print 'The first digit is {}'.format(val[0])
print 'The second digit is {}'.format(val[1])
print 'The third digit is {}'.format(val[2])
Changing the input from str
to int
will make digits impossible to separate, if you still want the input as integer you can wrap a int()
around the val[]
, like int(val[0])
.
Upvotes: 1
Reputation: 1407
try this code
val = raw_input ("Type your three digit number please:")#you must type 12 13 14
val=val+" "
list=[]
s=""
for i in val:
if i!=" ":
s=s+i
else:
list.append(int(s))
s=""
print list
output is
[12,13,14]
Upvotes: 0
Reputation: 9231
The simplest solution is to not treat is as an int
, I'd think:
digits = raw_input("Type your three digit number please")
print(list(digits)) # will print ['1', '2', '3']
Upvotes: 1