简体   繁体   English

用于用户输入的Python split def函数参数

[英]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. 我正在尝试将def函数参数拆分为两个用户输入,然后对两个值求和,然后打印出来。

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. 我想将“ print ab('1','111')”更改为用户输入。

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 我的结果:1,111

Expect result:1000 预期结果: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. 首先(如Daniel所言),您有函数调用Missing / Inproper。

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: 其次,您正在进行类型转换(将输入的类型从string更改为integer )-在函数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__'

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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