문제

I am writing a program where the user must input a number between 0 and 100. Then the program should split the number into 10's and 1's. So if the user inputs 23, the program would return 2 and 3. If the user input 4, the program would return 0 and 4. This is what I have for numbers less than 10, but I'm not sure how to handle 2 digit numbers using the modulo operator.

def split():
    number = int(raw_input("Enter a number between 0 and 100:"))
    if number <10:
        tens = 0
        ones = number
        total = tens + ones
        print "Tens:", tens
        print "Ones:", ones
        print "Sum of", tens, "and", ones, "is", total

split()

Thank you!

도움이 되었습니까?

해결책

Use the divmod function.

>>> a, b = divmod(23, 10)
>>> a, b
(2, 3)
>>> print "Tens: %d\nOnes: %d" % divmod(23, 10)
Tens: 2
Ones: 3

Don't know about divmod? help is your friend!

>>> help(divmod)
Help on built-in function divmod in module __builtin__:

divmod(...)
    divmod(x, y) -> (quotient, remainder)

    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top