【问题标题】:Python split def function parameter for user inputPython split def 函数参数用于用户输入
【发布时间】:2016-10-28 09:45:44
【问题描述】:

我正在尝试将 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')

我想将“print 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

我的结果:1,111

预期结果:1000

【问题讨论】:

  • 请修正你的缩进...
  • 你刚刚错过了ab电话吗?比如总计 = ab(b1,b2)

标签: python function input user-input


【解决方案1】:

我不知道你是如何在这里获得回报的。 首先(如丹尼尔)所说,您的函数调用丢失/不正确。

total = ab(b1,b2)

其次,您正在进行类型转换(将输入类型从 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__'

最终的工作代码必须是:

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

【讨论】:

    【解决方案2】:

    你没有在第二个 sn-p 中调用你的函数。

    total = ab(b1,b2)
    

    【讨论】:

    • 结果:TypeError:'int'对象没有属性'getitem'
    • 所以,问问自己为什么要将这些输入字符串转换为整数。在第一个 sn-p 中,您传递字符串。
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 2015-08-24
    • 2013-04-16
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多