Skip to main content
 首页 » 编程设计

python之在python中将2位数字拆分为1 0's and 1' s

2025年05月04日11think

我正在编写一个程序,用户必须在其中输入一个介于 0 和 100 之间的数字。然后程序应该将该数字分成 10 和 1。因此,如果用户输入 23,程序将返回 2 和 3。如果用户输入 4,程序将返回 0 和 4。这就是我对小于 10 的数字所拥有的,但我不确定如何处理 2使用模运算符的数字。

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() 

谢谢!

请您参考如下方法:

使用divmod函数。

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

不知道 divmod? help 是你的 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.