jace - 1 year ago 69
Python Question

# 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
if b1[-1] == '0':  # 0+1 or 0+0
if b2[-1] == '0':  # 1+0
#      V    NOTE   V <<< push overflow 1 to head

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
if b1[-1] == '0':  # 0+1 or 0+0
if b2[-1] == '0':  # 1+0
#      V    NOTE   V <<< push overflow 1 to head

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
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
if b1[-1] == '0':  # 0+1 or 0+0