Reputation: 123
I am currently trying to create a program that requests a 3 digit number from the user and prints out the individual digits of the number in order, eg:
"Input 3 digits: 123"
1
2
3
I am not allowed to use any form of strings, just mathematical operations.
Also, I have gotten formulas for the second and third digit but cannot get the first for the life of me, and when I run the program the first and the second digit return with a decimal number which I am not sure how to avoid.
My code:
n = eval(input('Enter a 3-digit number: '))
c = n % 10
b = n - c
b = b / 10
b = b % 10
a = n / b
a = a % 10
print(a)
print(b)
print(c)
Upvotes: 0
Views: 5394
Reputation: 1
num=int(input("enter your number: "))
a=num//100
b=(num%100)//10
c=(num%100)%10
Upvotes: -1
Reputation: 21
I think you are looking for this:
n = eval(input('Enter a 3-digit number: '))
c = n % 10
b = int(n / 10)
b = b % 10
a = int(n / 100)
a = a % 10
print(a)
print(b)
print(c)
Upvotes: 0
Reputation: 798
You get the input as a string so, using your example, you would get '123'. If you're not obligated to use the formulas, you could get each digit as follows:
user_input = input('Enter a 3-digit number: ')
first_digit, second_digit, third_digit = [int(digit) for digit in user_input]
print first_digit
print second_digit
print third_digit
Upvotes: 1
Reputation: 1237
THe problem is where you divide n by b -- no reason to divide the original number by its second digit. You probably wanted to divide by 10 again.
It's easier if you remember that when you divide integers, you get an integer -- so, for example: 329 / 10 gives 32 That save you from having to subtract at all (also, clearer variable names make it much more readable):
dig3 = n % 10
n = n/10
dig2 = n % 10
dig1 = n/10
Upvotes: 0
Reputation: 9986
There's a much easier way to do this that doesn't require any math. In Python, strings are iterable and input()
returns a string. So you can just do this:
n = input('enter a number: ')
for x in n:
print(x)
Upvotes: 2
Reputation: 14376
Divide your number by 100, inside of a call to int
:
Input 3 digits: 435
firstDigit = int(n / 100)
firstDigit will be 4
Upvotes: 1