2016-10-28 23 views
0

我想将拆分def函数参数分成两个用户输入,然后总结两个值然后打印出来。用户输入的Python拆分def函数参数

示例代码:

def ab(b1, b2): 
if not (b1 and b2): # b1 or b2 is empty 
    return b1 + b2 
head = ab(b1[:-1], b2[:-1]) 
if b1[-1] == '0': # 0+1 or 0+0 
    return head + b2[-1] 
if b2[-1] == '0': # 1+0 
    return head + '1' 
#  V NOTE V <<< push overflow 1 to head 
return ab(head, '1') + '0' 


print ab('1','111') 

我想改变 “打印AB( '1', '111')” 到用户输入。

我的代码:

def ab(b1, b2): 
if not (b1 and b2): # b1 or b2 is empty 
    return b1 + b2 
head = ab(b1[:-1], b2[:-1]) 
if b1[-1] == '0': # 0+1 or 0+0 
    return head + b2[-1] 
if b2[-1] == '0': # 1+0 
    return head + '1' 
#  V NOTE V <<< push overflow 1 to head 
return ab(head, '1') + '0' 

b1 = int(raw_input("enter number")) 
b2 = int(raw_input("enter number")) 


total = (b1,b2) 

print total 

我的结果:1111

期望的结果:1000

+2

请修复您的缩进... – DavidG

+1

您刚刚错过了ab通话吗? like total = ab(b1,b2) –

回答

2

我不知道你是如何得到回报在这里工作。 首先(如丹尼尔)所述,你有这个函数调用丢失/不正确。

total = ab(b1,b2) 

其次,你的类型转换(改变输入的类型从stringinteger) - 在你的函数ab你在b1b2,这将导致异常应用字符切片:

Traceback (most recent call last): 
    File "split_def.py", line 33, in <module> 
    total = ab_new(b1,b2) 
    File "split_def.py", line 21, in ab_new 
    head = ab_new(b1[:-1], b2[:-1]) 
TypeError: 'int' object has no attribute '__getitem__' 

最后的工作代码必须是:

def ab(b1, b2): 
    if not (b1 and b2): # b1 or b2 is empty 
     return b1 + b2 
    head = ab(b1[:-1], b2[:-1]) 
    if b1[-1] == '0': # 0+1 or 0+0 
     return head + b2[-1] 
    if b2[-1] == '0': # 1+0 
     return head + '1' 
    #  V NOTE V <<< push overflow 1 to head 
    return ab(head, '1') + '0' 

b1 = raw_input("enter number") 
b2 = raw_input("enter number") 

total = ab(b1,b2) 

print "total", total 
1

你没有打电话给你的函数在第二个片段。

total = ab(b1,b2) 
+0

结果:TypeError:'int'object has no attribute'__getitem__' – terry

+0

因此,问问自己为什么要将这些输入字符串转换为整数。在第一个片段中,你传递了字符串。 –