简体   繁体   中英

Python split def function parameter for user input

i'm trying to do split def function parameter into two user input then sum up both value then print out.

Example code:

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

I would like to change "print ab('1','111')" to user input.

My code:

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

My result: 1,111

Expect result:1000

I don't know how you're getting the return working here. First of all (as Daniel) stated, you have the function call missing/improper.

total = ab(b1,b2)

Secondly, you're type-casting (changing type of input from string to integer ) - and in your function ab you're applying string slicing on the b1 and b2 , which will result in an exception:

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__'

The final working code has to be:

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

您没有在第二个片段中调用函数。

total = ab(b1,b2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM