python脚本在嵌套的if语句中给出typerror

时间:2016-04-08 04:30:59

标签: python

我试图在python中第一次编写一个简单的乘法程序,我得到以下错误,不知道为什么。我的代码也发布在下面。

    #!/usr/bin/env python
    from math import *

    def main():
        multiplier = raw_input('multiplier?')
        multiplicand = raw_input('multiplicand?')
        print (recursive(multiplier, multiplicand))

    def recursive(multiplier, multiplicand):
            if (multiplier == 0):
            answer = 0
        if (multiplier == 1):
            answer = multiplicand
        if ((multiplier > 1) & ((multiplier % 2) == 0)):
            answer = recursive((multiplier/2), (multiplicand*2))
        if ((multiplier > 1) & ((multiplier % 2) == 1)):
            answer = (multiplicand + (recursive((multiplier/2), (multiplicand*2))))
        return answer

    main()

错误:

multiplier?5
multiplicand?5
Traceback (most recent call last):
  File "./multiplication.py", line 20, in <module>
    main()
  File "./multiplication.py", line 7, in main
    print (recursive(multiplier, multiplicand))
  File "./multiplication.py", line 14, in recursive
    if ((multiplier > 1) & ((multiplier % 2) == 0)):
TypeError: not all arguments converted during string formatting

2 个答案:

答案 0 :(得分:0)

乘数是一个字符串,因此模数运算符试图在字符串中放置一个值,就像你在字符串string = "%s%d..."中看到的那样。因此转换错误。而不是进行mod操作。您需要将变量multiplier转换为int(或float)。

答案 1 :(得分:0)

multiplier作为字符串传递,而不是数字。这是因为raw_input()总是返回一个字符串。要转换它,请执行float(raw_input())

错误是因为%运算符返回两个数字的余数,但您的字符串不是有效的格式字符串。

7 % 2 == 1

但是当第一个是字符串时它会进行字符串格式化

'%d dogs ' % 2 == '2 dogs'